useStickyState


The useState React hook is great for state that should be freshly initialized on every visit, but what about for state that should be persisted between sessions?

A good example of this is filters. If I set a filter to sort based on price instead of newest items, that value should "stick", so that if I come back to this site in a week, it remembers that I want to sort by price.

The useStickyState hook works just like useState, except it backs up to (and restores from) localStorage.

Usage

import { useStickyState } from 'reactchemy'

export default function Component() {
   const [count, setCount] = useStickyState(0, 'count')

   const increment = () => {
      setCount((prevCount: number) => prevCount + 1)
   }

   return (
       <div>
          <h2>useStickyState Demo</h2>
          <p>Count: {count}</p>
          <button onClick={increment}>Increment</button>
       </div>
   )
}

Hook

import { useEffect, useState } from 'react'

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