@olerichter00/use-localstorage
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

use-localstorage

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.

CI status DeepSource DeepScan grade npm version

CodeSandbox

Install

Install with NPM:

npm i --save @olerichter00/use-localstorage

Install with Yarn:

yarn add @olerichter00/use-localstorage

Usage

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)

License

The npm package is available as open source under the terms of the MIT License.

Package Sidebar

Install

npm i @olerichter00/use-localstorage

Weekly Downloads

1

Version

0.1.1

License

MIT

Unpacked Size

19.6 kB

Total Files

13

Last publish

Collaborators

  • olerichter00