Problem Statement
How to manage localStorage or sessionStorage with hooks?
Explanation
You can build a custom hook that syncs state with localStorage. Whenever state changes, save it to storage and initialize from storage on load.
Code Solution
SolutionRead Only
function useLocal(key,init){
const [val,setVal]=useState(()=>JSON.parse(localStorage.getItem(key))||init);
useEffect(()=>localStorage.setItem(key,JSON.stringify(val)),[val]);
return [val,setVal];
}Practice Sets
This question appears in the following practice sets: