Custom hook to persist React state on browser
If you're looking to persist React Native state, check out react-native-sticky-state
In your React project folder, run:
npm i use-sticky-state --save
import useStickyState from "use-sticky-state";
const App = () => {
const [count, setCount] = useStickyState(0, "counter-key");
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>{count}</p>
</div>
);
};
const [state, setState] = useStickyState(defaultValue, storageKey);
Property | Description |
---|---|
defaultValue | The default value used if storageKey was not previously set |
storageKey | Unique string key used to persist data, using your browser's built in localStorage API |