Similar to useState
but with some lightweight behind-the-scenes
writing to localStorage; also subscribes to changes in localStorage
to allow for cross-tab changes to sync automatically.
The first argument is the name of the local storage property/key you want to control with this hook. The second argument,
options
, really just has one available directive: bool
. Setting bool
to true
has the effect of evaluating the data
returned from getItem
as a boolean (otherwise it's always a string).
import useStorage from "./useLocalStorage.js"
const App = () => {
const [darkMode, setDarkMode] = useStorage("dark-mode", { bool: true })
return (
<div
style={{
background: darkMode ? "#333" : "#eee",
color: darkMode ? "#bbb" : "#333",
}}
>
Hello, world!
</div>
)
}
export default App