React Hooks: useLocalStorageState
In some cases you want to save the state, so the next time the user visits your page it uses the saved version.
Usage
The usage of this hook is similar to React's useState
hook. Except we take a key as first parameter. For this hook we use our custom useImmutableCallback hook
Example
Every time you refresh your page, the counter will start on the value you left.
export default function Counter() {
let [count, setCount] = useLocalStorageState('count', 0);
function handleClick() {
setCount(count + 1);
}
return <button onClick={handleClick}>Clicked {count} times</button>
}
The hook
import { useState } from 'react';
import useImmutableCallback from './use-immutable-callback';
function initialState(initialValue) {
if (typeof initialValue === 'function') {
return initialValue();
} else {
return initialValue;
}
};
export default function useLocalStorageState(key, initialValue) {
let [data, setState] = useState(function () {
try {
let localData = window.localStorage.getItem(key);
if (localData) {
return JSON.parse(window.localStorage.getItem(key));
} else {
return initialState(initialValue);
}
} catch (error) {
return initialState(initialValue);
}
});
let setData = useImmutableCallback(function (value) {
window.localStorage.setItem(key, JSON.stringify(value));
setState(value);
});
return [data, setData];
}
If you have any questions, I'm @WardPoel on Twitter.