Open In App

How to persist state with Local or Session Storage in React ?

Persisting state with localStorage or sessionStorage is a way to store data in the user’s web browser so that it remains available even after the page is refreshed or closed.

Persisting state with localStorage or sessionStorage:

To persist state using React’s useState hook along with localStorage, you can follow these steps:



Example: Below is an example of persisting state with localStorage or sessionStorage.




import React, {
    useState,
    useEffect
} from 'react';
 
function Counter() {
    const [count, setCount] = useState(() => {
        const storedCount = localStorage.getItem('count');
        return storedCount ? parseInt(storedCount) : 0;
    });
 
    useEffect(() => {
        localStorage.setItem('count', count.toString());
    }, [count]);
 
    const increment = () => {
        setCount(prevCount => prevCount + 1);
    };
 
    const decrement = () => {
        setCount(prevCount => prevCount - 1);
    };
 
    return (
        <div>
            <h1>Counter: {count}</h1>
            <button onClick={increment}>Increment</button>
            <button onClick={decrement}>Decrement</button>
        </div>
    );
}
 
export default Counter;

Output:




Article Tags :