Skip to main content

useLocalStorage

Technically, this is a wrapper hook for window.localStorage. With the features of Hook, you can inject the localStorage (as a reusable stateful logic) to React lifecycle. This hook can play well with useContext to manage states across the components tree.

Authentication.jsx
import { useLocalStorage } from "@trakas/react";
export function Authentication() {
const [token, setToken, clearToken] = useLocalStorage("token");
const handleAuthenticate = () => {
if (!token) {
setToken("this is super secret!");
} else {
clearToken();
}
};
return (
<div>
<button onClick={handleAuthenticate}>{token ? "Log out" : "Login"}</button>
<div>Token: {token}</div>
<div>Token (localStorage): {JSON.stringify(localStorage.getItem("token"))}</div>
</div>
);
}

Options#

const [storedValue, setValue, clearValue] = useLocalStorage(key, initialValue);
  • key: string
    • Required
    • The key to store data to localStorage
  • initialValue: T | undefined
    • Optional
    • Defaults to undefined
    • The initial value when there is no value is stored in localStorage

Returns#

  • storedValue: T | undefined
    • The value was stored to localStorage.
  • setValue: (value: T) => void
    • Update the value in localStorage and the storedValue
  • clearValue: () => void
    • Remove the value in localStorage and update storedValue to initialValue
note

Basically, the value that you can store in localStorage can be any thing.

useLocalStorage uses JSON.parse to parse value from localStorage. So if the value was stored is one of the falsy values, storedValue will get the value from initialValue.