A React Hook to persist data locally.
Install with npm
npm i react-hook-persist-data
Install with yarn
yarn add react-hook-persist-data
In its most basic form, the useLocalStorage
hook just needs the Local Storage key
you wish to use. However, it's advised that you also provde a default value as a second argument in the event that the key
does not yet exist in Local Storage.
The following usage will persist the username
variable in a "name"
key in Local Storage. It will have a default/initial value of an empty string ""
. This default value witll only be used if there is no value already in Local Storage.
import useLocalStorage from "react-hook-persist-data";
function MyComponent() {
const [username, setUsername] = useLocalStorage("name", "");
return (
<>
<input
value={username}
onChange={(e) => {
setUsername(e.target.value);
}}
/>
</>
);
}