
Local Storage in React
When we are developing any app, we need to store data. It can be stored at backend and every time we need data, we can call API and get it. But if it is possible to store data at browser end, then it will make application faster and server load can be minimized.
To persist state in React, we can use the native local storage of the browser. The article gives you a step by step showcase on how to persist state in React with local storage, how to use it as a cache for data in a more elaborate example.
What is local storage?
The read-only localStorage property allows you to store and access data across browser sessions. Data stored in localStorage has no expiration time like sessionStorage. The data is always stored in key value pair. The usage of the local storage is fairly straight forward. In your JavaScript code, running in the browser, you should have access to the localStorage instance which has setter and getter to store and retrieve data from the local storage. There are also methods on the local storage to remove items and to clear all items:
// setter
localStorage.setItem('userName', userName);
// getter
localStorage.getItem('userName');
// remove
localStorage.removeItem('userName');
// remove all
localStorage.clear();Using LOCAL STORAGE IN REACT
Lets create example with React function component which uses React Hooks to manage state of input field. The result of input is shown in paragraph.
import React from 'react';
const App = () => {
const [userName, setUserName] = React.useState('');
const handleChange = event => setUserName(event.target.value);
return (
<div>
<h1>Local Storage in React!</h1>
<input value={userName} type="text" onChange={handleChange} />
<p>{userName}</p>
</div>
);
};
export default App;As we have not yet stored state in local storage, it gets lost if you refresh page or close browser tab. The solution is to add state whenever it changes. We can store changes made by using handleChange function, but updating the local storage in React’s function components is a side-effect which is best implemented with the Effect Hook which runs every time the value property changes.
React.useEffect(() => {
localStorage.setItem('userName', userName);
}, [userName]);We passed second argument to restrict the useEffect to be called only when userName is updated.
Now lets retrieve ‘userName’ stored in local storage and set it when component gets rendered.
const [userName, setUserName] = useState( localStorage.getItem('userName') || '' );To Do:
/ /remove item
// clear all from local storage
// news api with axios and store object in local storage



