A react hook that uses the local storage API to store values and communicate between components. The hook is designed to be used with SSR frameworks like NextJS or Gatsby.
Install with NPM:
npm i --save @olerichter00/use-localstorage
Install with Yarn:
yarn add @olerichter00/use-localstorage
use-localstorage can either be initialized with a value or with a function that returns the initial value. This is especially helpful with SSR if the inital value is only available in the browser environment (like document
or window
).
Usage with an inital value
import React from 'react'
import useLocalStorage from './useLocalStorage'
export default function App() {
const [count, setCount] = useLocalStorage<number>('counter', 1)
return (
<div className="App">
<button onClick={() => setCount(count + 1)}>+</button>
<div>Count: {count}</div>
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
Usage with a function as inital value
import React from 'react'
import useLocalStorage from '@olerichter00/use-localstorage'
export default function App() {
const darkColorScheme = () =>
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
const [darkMode, setDarkMode] = useLocalStorage<boolean>('dark-mode', darkColorScheme)
return (
<div
className="App"
style={{
backgroundColor: darkMode ? 'black' : 'white',
}}
>
<button onClick={() => setDarkMode(!darkMode)}>Switch Color</button>
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
The npm package is available as open source under the terms of the MIT License.