I have a react application which I am using context API as a state management in it. I get the a specific value from the server, assign it to a component state and then store it as the context value. But, the problem is that any time the page refreshes and reloads, the context value gets cleared as the aforementioned state is lost. Is there a way to store and keep this value even if the page reload? Is there any way other than local Storage?
I really appreciate any help.
Advertisement
Answer
The example below is a custom hook that uses the Storage API to get and save values. It works similar to a useState
hook but uses a keyName
string to specify the name of the key in the storage get and set the value in.
Using this hooks allows your context provider component to get and save it’s values permanently on the user’s device.
import { useState, useEffect } from 'react' const useLocalStorage = keyName => { const [value, setValue] = useState(() => { const storedValue = localStorage.getItem(keyName); try { const parsedValue = JSON.parse(storedValue); return parsedValue; } catch(error) { return storedValue; } }); useEffect(() => { const stringifiedValue = JSON.stringify(value); localStorage.setItem(keyName, stringifiedValue); }, [value]); return [value, setValue]; }; export default useLocalStorage
Example of usage:
import useLocalStorage from './useLocalStorage'; const Component () => { const [value, setValue] = useLocalStorage('user'); ... };