aboutsummaryrefslogtreecommitdiffstats
path: root/src/hooks/useStickyState.js
blob: 237362a66d2e785e537aaa24435b3a13cef41bbb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { useEffect, useState } from 'react'

const useStickyState = (defaultValue, key) => {
  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]
}

export default useStickyState