How to manage local storage in React?

To manage local storage in React, you can follow these steps:

  1. Use the useState hook to create a state variable that will hold the data you want to store in local storage.

  2. Use the useEffect hook to retrieve the data from local storage when the component mounts and update the state variable with that data.

  3. Use the useEffect hook to save the data to local storage whenever the state variable changes.

Here is an example of how you can manage local storage in React:

import React, { useState, useEffect } from 'react'; const App = () => { const [data, setData] = useState(''); useEffect(() => { const storedData = localStorage.getItem('data'); if (storedData) { setData(storedData); } }, []); useEffect(() => { localStorage.setItem('data', data); }, [data]); const handleChange = (e) => { setData(e.target.value); }; return ( <div> <input type="text" value={data} onChange={handleChange} /> </div> ); }; export default App;

This example demonstrates how to store and retrieve data from local storage in a React component using the useState and useEffect hooks. The data is stored in local storage whenever the input value changes, and it is retrieved from local storage when the component mounts.