Skip to content

useLocalStorage

Store a data to browser local storage using this hooks

Abdul

Created by / Abdul

JS
const useLocalStorage = (key, initialValue) => {
  const [value, setValue] = useState(() => {
    try {
      return localStorage.getItem(key) || initialValue
    } catch (error) {
      console.log('there is an error with local storage:', error)
      return initialValue
    }
  })

  useEffect(() => {
    window.localStorage.setItem(key, value)
  }, [value])

  return [value, setValue]
}

Usage

JSX
const App = () => {
  const [username, setUsername] = useLocalStorage('username', 'up2dul')

  return <input type='text' value={username} onChange={({ target }) => setUsername(target.value)} />
}