1.0.4 • Published 4 years ago

@nicer-toolbox/use-sticky-state v1.0.4

Weekly downloads
46
License
MIT
Repository
github
Last release
4 years ago

Nicer Toolbox

Use Sticky State

Persisting React State in localStorage

NPM JavaScript Style Guide

Usage

function App() {
  const [count, setCount] = useStickyState(0, 'count')

  return (
    <div className='App'>
      <h1>Counter</h1>
      <p>Current count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  )
}

Code Behind The Scenes

function useStickyState(defaultValue, key) {
  const [value, setValue] = React.useState(() => {
    const stickyValue = window.localStorage.getItem(key)
    return stickyValue !== null ? JSON.parse(stickyValue) : defaultValue
  })
  React.useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(value))
  }, [key, value])
  return [value, setValue]
}
1.0.4

4 years ago

1.0.3

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago