Solution
To use localstorage in react js functional component, you have to use localstorage
with react hooks depending upon the situation.
Snippet
In this snippet, we will use react hooks with localstorage
for the following points.
- Get data from localstorage when the component load
- Store data on localstorage when the component load
- Store data on localstorage when a state change
Get data from localstorage when the component load
On a load of components, sometimes we need to fetch data from local storage and store it in a state to show in the UI.
const [items, setItems] = useState([]);
useEffect(() => {
const items = JSON.parse(localStorage.getItem('items'));
if (items) {
setItems(items);
}
}, []);
Store data on localstorage when the component load
On the other hand, we have some components where we have to call API at the time the component load and store data in localstorage
.
const [items, setItems] = useState([]);
useEffect(() => {
// array which you get from API Response
let arr = ["aGuideHub", "SortoutCode", "Infinitbility"];
if (arr) {
localStorage.setItem("items", JSON.stringify(arr));
setItems(arr);
}
}, []);
Store data on localstorage when a state change
In the last case, we have to update localStorage
when the state change to keep data in sync.
const [items, setItems] = useState([]);
useEffect(() => {
localStorage.setItem('items', JSON.stringify(items));
}, [items]);