React js Local Storage Practice Questions with Solutions

Introduction

Local Storage allows a web application to store small amounts of data in the user’s browser so that the data can remain available across page reloads and browser sessions. In React, localStorage is commonly used for preferences, simple settings, saved items, and small client-side data. In this chapter, we will solve practical questions on storing, reading, updating, and removing data from Local Storage using React state and browser APIs. React js Local Storage practice questions with solutions help to understand the concepts.

1. What is Local Storage in React?

Local Storage is a browser feature that allows websites to store data as key-value pairs.

For example:

localStorage.setItem("username", "Rahul");

The value can later be retrieved using:

localStorage.getItem("username");

Local Storage data normally remains available after refreshing the page and reopening the browser.

React does not provide localStorage itself. It is a browser Web API that React applications can use.


2. How do you store data in Local Storage using React?

You can use localStorage.setItem() to save a value.

Solution:

import { useState } from "react";

function App() {
  const [name, setName] = useState("");

  const saveName = () => {
    localStorage.setItem("username", name);
  };

  return (
    <div>
      <input
        value={name}
        onChange={(event) => setName(event.target.value)}
        placeholder="Enter your name"
      />

      <button onClick={saveName}>
        Save Name
      </button>
    </div>
  );
}

export default App;

Here:

localStorage.setItem("username", name);

stores the value using username as the key.


3. How do you get data from Local Storage in React?

Use localStorage.getItem().

Solution:

import { useState } from "react";

function App() {
  const [name, setName] = useState("");

  const loadName = () => {
    const savedName = localStorage.getItem("username");

    if (savedName) {
      setName(savedName);
    }
  };

  return (
    <div>
      <button onClick={loadName}>
        Load Name
      </button>

      <h2>{name}</h2>
    </div>
  );
}

export default App;

The getItem() method returns the stored value or null if the key does not exist.


4. How do you save React state to Local Storage?

You can use useEffect() to save state whenever the value changes.

Solution:

import { useEffect, useState } from "react";

function App() {
  const [name, setName] = useState("");

  useEffect(() => {
    localStorage.setItem("username", name);
  }, [name]);

  return (
    <div>
      <input
        value={name}
        onChange={(event) => setName(event.target.value)}
        placeholder="Enter your name"
      />

      <h2>Hello {name}</h2>
    </div>
  );
}

export default App;

Whenever name changes, the effect stores the latest value in Local Storage.


5. How do you initialize React state from Local Storage?

You can read Local Storage when initializing state.

A lazy initializer is useful because the browser storage read is performed when the initial state is created.

Solution:

import { useState } from "react";

function App() {
  const [name, setName] = useState(() => {
    return localStorage.getItem("username") || "";
  });

  return (
    <div>
      <input
        value={name}
        onChange={(event) => setName(event.target.value)}
      />

      <h2>{name}</h2>
    </div>
  );
}

export default App;

If username exists in Local Storage, it becomes the initial state value.


6. How do you store an array in Local Storage?

Local Storage stores strings, so arrays should be converted to JSON using JSON.stringify().

Solution:

const products = [
  "Laptop",
  "Mobile",
  "Keyboard"
];

localStorage.setItem(
  "products",
  JSON.stringify(products)
);

To read the array again:

const savedProducts = JSON.parse(
  localStorage.getItem("products") || "[]"
);

console.log(savedProducts);

The result is:

[
  "Laptop",
  "Mobile",
  "Keyboard"
]

JSON.stringify() converts JavaScript data into a string, while JSON.parse() converts the stored JSON string back into JavaScript data.


7. How do you store an object in Local Storage?

Objects also need to be converted into a string before storing them.

Solution:

const user = {
  name: "Rahul",
  age: 22,
  city: "Delhi"
};

localStorage.setItem(
  "user",
  JSON.stringify(user)
);

To retrieve the object:

const savedUser = JSON.parse(
  localStorage.getItem("user") || "null"
);

console.log(savedUser);

You can then access its properties:

console.log(savedUser?.name);

The optional chaining operator helps avoid an error if no object was stored.


8. How do you remove data from Local Storage?

Use localStorage.removeItem().

Solution:

localStorage.removeItem("username");

In React:

import { useState } from "react";

function App() {
  const [name, setName] = useState(
    () => localStorage.getItem("username") || ""
  );

  const removeName = () => {
    localStorage.removeItem("username");
    setName("");
  };

  return (
    <div>
      <h2>{name}</h2>

      <button onClick={removeName}>
        Remove Name
      </button>
    </div>
  );
}

export default App;

Removing the Local Storage item and updating React state keeps the UI synchronized with the stored data.


9. How do you create a Todo List using Local Storage?

You can save the Todo array whenever it changes and load it when the component initializes.

Solution:

import { useEffect, useState } from "react";

function TodoApp() {
  const [todos, setTodos] = useState(() => {
    const savedTodos = localStorage.getItem("todos");

    return savedTodos
      ? JSON.parse(savedTodos)
      : [];
  });

  const [text, setText] = useState("");

  useEffect(() => {
    localStorage.setItem(
      "todos",
      JSON.stringify(todos)
    );
  }, [todos]);

  const addTodo = () => {
    if (!text.trim()) {
      return;
    }

    const newTodo = {
      id: Date.now(),
      text: text
    };

    setTodos((currentTodos) => [
      ...currentTodos,
      newTodo
    ]);

    setText("");
  };

  const deleteTodo = (id) => {
    setTodos((currentTodos) =>
      currentTodos.filter(
        (todo) => todo.id !== id
      )
    );
  };

  return (
    <div>
      <h2>Todo List</h2>

      <input
        value={text}
        onChange={(event) => setText(event.target.value)}
        placeholder="Enter a todo"
      />

      <button onClick={addTodo}>
        Add Todo
      </button>

      {todos.map((todo) => (
        <div key={todo.id}>
          <span>{todo.text}</span>

          <button
            onClick={() => deleteTodo(todo.id)}
          >
            Delete
          </button>
        </div>
      ))}
    </div>
  );
}

export default TodoApp;

The important part is:

useEffect(() => {
  localStorage.setItem(
    "todos",
    JSON.stringify(todos)
  );
}, [todos]);

Whenever the Todo state changes, the updated array is saved.


10. How do you create a React theme preference using Local Storage?

Local Storage can be used to remember a user’s selected theme.

Solution:

import { useEffect, useState } from "react";

function App() {
  const [theme, setTheme] = useState(() => {
    return localStorage.getItem("theme") || "light";
  });

  useEffect(() => {
    localStorage.setItem("theme", theme);
  }, [theme]);

  const toggleTheme = () => {
    setTheme((currentTheme) =>
      currentTheme === "light"
        ? "dark"
        : "light"
    );
  };

  return (
    <div
      style={{
        background:
          theme === "dark"
            ? "#222"
            : "#fff",
        color:
          theme === "dark"
            ? "#fff"
            : "#222",
        minHeight: "100vh",
        padding: "20px"
      }}
    >
      <h2>
        Current Theme: {theme}
      </h2>

      <button onClick={toggleTheme}>
        Toggle Theme
      </button>
    </div>
  );
}

export default App;

When the user selects a theme, the preference is stored:

localStorage.setItem("theme", theme);

When the application loads again, the stored theme is used as the initial state.

Key Takeaways

  • Local Storage is a browser Web API, not a React-specific feature.
  • localStorage.setItem() stores data.
  • localStorage.getItem() retrieves data.
  • localStorage.removeItem() removes a specific item.
  • Local Storage stores values as strings.
  • Use JSON.stringify() to store arrays and objects.
  • Use JSON.parse() to convert stored JSON back into JavaScript data.
  • useState() can initialize React state from Local Storage.
  • useEffect() can synchronize state changes with Local Storage.
  • Local Storage is useful for small client-side data such as preferences and simple saved items.
  • Do not store passwords, authentication secrets, or other sensitive information in Local Storage.
  • Local Storage is not a replacement for a database or server-side storage.

FAQs

1. What is Local Storage in React?

Local Storage is a browser API that allows a React application to store small amounts of string-based data in the user’s browser.

2. Does React provide Local Storage?

No. Local Storage is provided by the browser. React applications can use the browser’s localStorage API.

3. Can Local Storage store arrays and objects?

Yes, but Local Storage stores strings. Therefore, arrays and objects are usually converted using JSON.stringify() before storing and JSON.parse() after retrieving.

4. Does Local Storage data remain after refreshing the page?

Yes. Data stored in Local Storage normally remains after a page refresh and can remain available when the browser is reopened, until the data is removed or browser storage is cleared.

5. What is the difference between Local Storage and React state?

React state is used to manage data that affects the component’s UI and causes React to render updates. Local Storage persists data in the browser across page reloads. They can be used together when an application needs both reactive UI state and persistence.

6. Should passwords be stored in Local Storage?

No. Local Storage should not be used to store passwords or other sensitive authentication secrets. Applications should use appropriate secure authentication and server-side mechanisms.

7. Can Local Storage be used with a Todo application?

Yes. A Todo array can be converted to JSON and stored in Local Storage. When the application loads, the stored JSON can be parsed and used as the initial Todo state.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top