import React, { useState, useEffect } from "react";
const usePersistedState = (key, defaultValue, stringified = false) => {
const [state, setState] = useState(
() => (stringified ? JSON.parse(localStorage.getItem(key)) : localStorage.getItem(key) ) || defaultValue
);
useEffect(() => {
localStorage.setItem(key, stringified ? JSON.stringify(state) : state);
}, [key, state]);
return [state, setState];
};
export default usePersistedState;
stringified
is an optional third parameter to indicate if your state is stringified or not.
Example Usage
const [data, setData] = usePersistedState('myData', {}, true); // data is stringified
const [token, setToken] = usePersistedState('myToken', null);
setToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9')