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
#
Optionskey: 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
#
ReturnsstoredValue: T | undefined
- The value was stored to localStorage.
setValue: (value: T) => void
- Update the value in localStorage and the
storedValue
- Update the value in localStorage and the
clearValue: () => void
- Remove the value in localStorage and update
storedValue
toinitialValue
- Remove the value in localStorage and update
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
.