Solution
To use sessionstorage in react js functional component, you have to use sessionstorage
with react hooks depending upon the situation.
Snippet
In this snippet, we will use react hooks with sessionstorage
for the following points.
- Get data from sessionstorage when the component load
- Store data on sessionstorage when the component load
- Store data on sessionstorage when a state change
Get data from sessionstorage 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(sessionStorage.getItem('items'));
if (items) {
setItems(items);
}
}, []);
Store data on sessionstorage 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 sessionstorage
.
const [items, setItems] = useState([]);
useEffect(() => {
// array which you get from API Response
let arr = ["aGuideHub", "SortoutCode", "Infinitbility"];
if (arr) {
sessionStorage.setItem("items", JSON.stringify(arr));
setItems(arr);
}
}, []);
Store data on sessionstorage when a state change
In the last case, we have to update sessionStorage
when the state change to keep data in sync.
const [items, setItems] = useState([]);
useEffect(() => {
sessionStorage.setItem('items', JSON.stringify(items));
}, [items]);