Lesson 50 of 60 – Local Storage
83%

Local Storage in React

localStorage is a browser feature that allows web applications to store data in the user's browser. React applications can use localStorage to save small pieces of data that should remain available after a page is refreshed or the browser is reopened.

Note: localStorage stores data as strings. When storing objects or arrays, use JSON.stringify(), and when reading them back, use JSON.parse().

1. What is localStorage?

localStorage is a browser storage mechanism used to store key-value data.

localStorage

The stored data belongs to the website's browser storage area.

2. Why Use localStorage?

React applications can use localStorage when some small pieces of data need to remain available between page loads.

Examples include:

  • User preferences
  • Theme selection
  • Shopping cart information
  • Recently selected options
  • Simple application settings

3. localStorage Key-Value Structure

Data in localStorage is stored using a key and a value.

key → value

For example:

"username" → "Rahul"

4. setItem()

The setItem() method stores a value in localStorage.

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

Here, username is the key and Rahul is the value.

5. getItem()

The getItem() method retrieves a value from localStorage.

const username =
    localStorage.getItem("username");

console.log(username);

If the key exists, its stored value is returned.

6. removeItem()

The removeItem() method removes a specific key from localStorage.

localStorage.removeItem(
    "username"
);

7. clear()

The clear() method removes all localStorage entries for the current website's storage area.

localStorage.clear();
Warning: Use clear() carefully because it removes all localStorage data for that website.

8. localStorage Stores Strings

localStorage stores values as strings.

localStorage.setItem(
    "age",
    25
);

const age =
    localStorage.getItem("age");

console.log(typeof age);

The retrieved value is a string, even if a number was originally provided.

9. Storing Numbers

Numbers can be stored, but they are retrieved as strings.

localStorage.setItem(
    "age",
    "25"
);

const age =
    Number(
        localStorage.getItem("age")
    );

console.log(age);

10. Storing Boolean Values

Boolean values can be converted to strings before storing them.

localStorage.setItem(
    "isLoggedIn",
    "true"
);

const isLoggedIn =
    localStorage.getItem(
        "isLoggedIn"
    ) === "true";

console.log(isLoggedIn);

11. JSON.stringify()

Objects cannot be stored directly in their original JavaScript object form. Use JSON.stringify() to convert an object into a JSON string.

const student = {
    name: "Rahul",
    course: "React"
};

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

12. JSON.parse()

Use JSON.parse() to convert the stored JSON string back into a JavaScript value.

const student =
    JSON.parse(
        localStorage.getItem("student")
    );

console.log(student.name);

13. Storing an Array

Arrays can also be stored using JSON.

const courses = [
    "HTML",
    "CSS",
    "React"
];

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

14. Reading an Array

const courses =
    JSON.parse(
        localStorage.getItem("courses")
    );

console.log(courses);

After parsing, the value can be used as a normal JavaScript array.

15. Using localStorage in React

React components can read and write localStorage using normal browser JavaScript APIs.

function App() {

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

    return <h2>React App</h2>;
}

However, storage operations should be designed carefully so they do not cause unnecessary work during rendering.

16. Reading localStorage with useState

A stored value can be used as the initial state.

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

The function form allows the initial value to be read when the state is initialized.

17. Saving State to localStorage

useEffect can synchronize React state with localStorage.

useEffect(() => {

    localStorage.setItem(
        "name",
        name
    );

}, [name]);

Whenever name changes, the stored value is updated.

18. Complete State Persistence Example

import {
    useEffect,
    useState
} from "react";

function App() {

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

    useEffect(() => {

        localStorage.setItem(
            "name",
            name
        );

    }, [name]);

    return (
        <div>

            <input
                value={name}
                onChange={e =>
                    setName(e.target.value)
                }
            />

            <p>
                Hello {name}
            </p>

        </div>
    );
}

export default App;

19. localStorage and Theme Selection

A theme preference can be stored so that the selected theme remains after a page refresh.

localStorage.setItem(
    "theme",
    "dark"
);

The application can read the value when it starts.

const theme =
    localStorage.getItem("theme");

20. localStorage and Shopping Cart

A simple shopping cart can be stored as a JSON array.

const cart = [
    {
        id: 1,
        name: "Laptop",
        quantity: 1
    },
    {
        id: 2,
        name: "Mouse",
        quantity: 2
    }
];

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

21. Checking for Stored Data

If a key does not exist, getItem() returns null.

const name =
    localStorage.getItem("name");

if (name === null) {

    console.log(
        "No name stored"
    );

}

22. Using Default Values

A default value can be used when no stored value exists.

const name =
    localStorage.getItem(
        "name"
    ) || "Guest";

If the key does not contain a usable value, "Guest" can be used.

23. Removing Stored Data in React

A React button can remove a stored value.

function logout() {

    localStorage.removeItem(
        "user"
    );

    setUser(null);
}

This pattern can be useful when removing application preferences or session information stored in the browser.

24. localStorage and useEffect

When React state and localStorage need to stay synchronized, useEffect is commonly used.

useEffect(() => {

    localStorage.setItem(
        "username",
        username
    );

}, [username]);

The dependency array makes the effect run when username changes.

25. localStorage and JSON State

Objects stored in localStorage should be serialized and parsed.

useEffect(() => {

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

}, [student]);

To read it:

const savedStudent =
    JSON.parse(
        localStorage.getItem("student")
    );

26. Common localStorage Mistakes

  • Forgetting that localStorage stores strings.
  • Trying to store objects without JSON.stringify().
  • Forgetting JSON.parse() when reading stored JSON.
  • Calling clear() when only one item should be removed.
  • Assuming stored data will always exist.
  • Storing sensitive information without understanding the security risks.
  • Putting unnecessary large amounts of application data into localStorage.
  • Creating unnecessary synchronization effects.

27. localStorage Workflow

React State
     ↓
JSON.stringify()
     ↓
localStorage
     ↓
getItem()
     ↓
JSON.parse()
     ↓
React State

This is a common pattern for persisting objects and arrays.

28. localStorage vs React State

React State localStorage
Manages UI state Stores data in the browser
Updates cause React re-rendering Changing storage does not automatically re-render React
Lives with the component/application state Can persist across page reloads
Useful for active UI data Useful for simple client-side persistence

29. Complete localStorage Example

import {
    useEffect,
    useState
} from "react";

function Profile() {

    const [user, setUser] = useState(
        () => {

            const savedUser =
                localStorage.getItem(
                    "user"
                );

            return savedUser
                ? JSON.parse(savedUser)
                : {
                    name: "",
                    course: ""
                };
        }
    );

    useEffect(() => {

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

    }, [user]);

    return (
        <div>

            <input
                value={user.name}
                placeholder="Name"
                onChange={e =>
                    setUser({
                        ...user,
                        name:
                            e.target.value
                    })
                }
            />

            <input
                value={user.course}
                placeholder="Course"
                onChange={e =>
                    setUser({
                        ...user,
                        course:
                            e.target.value
                    })
                }
            />

            <h3>
                {user.name}
            </h3>

            <p>
                {user.course}
            </p>

        </div>
    );
}

export default Profile;

30. localStorage Best Practices

  • Use meaningful and unique storage keys.
  • Remember that localStorage values are strings.
  • Use JSON.stringify() for objects and arrays.
  • Use JSON.parse() when reading stored JSON data.
  • Provide default values when stored data may not exist.
  • Use removeItem() when deleting one stored value.
  • Use clear() only when all site storage should be removed.
  • Keep localStorage data small and relevant.
  • Do not treat localStorage as a secure place for sensitive information.
  • Synchronize React state with storage carefully.
State
  ↓
JSON.stringify()
  ↓
localStorage
  ↓
getItem()
  ↓
JSON.parse()
  ↓
State

📌 Key Points

  • localStorage stores key-value data in the browser.
  • setItem() stores a value.
  • getItem() retrieves a value.
  • removeItem() removes a specific value.
  • clear() removes all localStorage entries for the site's storage area.
  • localStorage stores values as strings.
  • Use JSON.stringify() to store objects and arrays.
  • Use JSON.parse() to read stored JSON data.
  • useState and useEffect can be used to synchronize React state with localStorage.
  • Do not store sensitive information in localStorage without carefully considering the security implications.

🧠 Quick Quiz

Question: Which method is used to store a value in localStorage?