use localstorage react hook

How to Use LocalStorage React Hook

If you’re building a React app, you might want to store some data locally in the browser. LocalStorage is a great way to do this, and React has a built-in hook for it: the useLocalStorage hook.

Using the useLocalStorage Hook

The useLocalStorage hook is used to persist data in the browser's localStorage. It takes two arguments: the key you want to use to store the data and the initial value of that key.

import React, { useState } from 'react';
import useLocalStorage from './useLocalStorage';

function App() {
  const [name, setName] = useLocalStorage("name", "");

  function handleChange(event) {

      What's Your Name?
      Hello, {name}!

export default App;

In this example, we're using the useLocalStorage hook to store the user's name. We set the initial value to an empty string and pass in "name" as the key.

Whenever the user types their name into the input field, the handleChange function is called, which updates the value of the "name" key in localStorage by calling the setName function.

The value of the "name" key is then displayed on the screen with the <p> tag.

Multiple Ways to Implement LocalStorage Hook

There are several ways to implement the useLocalStorage hook. One way is to create a separate file for the hook and export it:

import { useState } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const storedValue = localStorage.getItem(key);
    return storedValue !== null ? JSON.parse(storedValue) : initialValue;

  function setLocalStorage(value) {
    localStorage.setItem(key, JSON.stringify(value));

  return [value, setLocalStorage];

export default useLocalStorage;

In this example, we're creating the useLocalStorage hook in a separate file called useLocalStorage.js. We define the hook using useState and set the initial value to either the value stored in localStorage or the provided initial value if no value is found.

We also define a setLocalStorage function that updates the value of the key in localStorage whenever the state changes.

We then export the hook so it can be used in other components.


The useLocalStorage hook is a great way to persist data in a React app. It's easy to use and can be implemented in several ways. Whether you choose to implement it in a separate file or directly in your component, it's a powerful tool for building great user experiences.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]