Skip to content

franlol/useLocalStorage

Repository files navigation

useLocalStorage - React custom hook

React custom Hook to manage localStorage API.

TL;DR;

Why useLocalStorage?

With this hook, you can handle your localStorage:

  • Manage and use it as a simple React State.
  • Don't need to call the Window interface.

Usage

Just install:

npm install react-hook-uselocalstorage

And import the hook:

import useLocalStorage from 'react-hook-uselocalstorage';

Use it in your component:

import React, { useRef } from 'react'
import useLocalStorage from 'react-hook-uselocalstorage'

const App = () => {
  const [storageVariable, setStorageVariable] = useLocalStorage('storage data');
  const inputRef = useRef(null);

  const clickHandler = () => {
    setStorageVariable(inputRef.current.value);
  }

  return (
    <div>
      <h2>{storageVariable}</h2>

      <input ref={inputRef} type='text' />
      <button onClick={clickHandler}>Set</button>
    </div>
  )
}

export default App

License

MIT © franlol