LocalStorage with React Hooks
Tags: react, javascript, tutorial, localstorage
Published: 2023-07-20 06:48:09

## How to Use localStorage with React Hooks to Set and Get Items

React is a popular JavaScript library for building user interfaces, and with the introduction of React Hooks, managing state and side effects has become even more straightforward. One common requirement in web development is to persist data locally, so users can access their preferences and settings across sessions. This is where localStorage comes into play. In this article, we will explore how to use localStorage with React Hooks to set and get items, providing a seamless user experience.



## Understanding localStorage

localStorage is a built-in web API provided by modern web browsers that allow web applications to store key-value pairs locally within the user's browser. The data stored in localStorage persists even after the user closes the browser or navigates away from the page. This makes it an excellent choice for storing temporary or user-specific data on the client side.



React Hooks are a set of functions introduced in React 16.8 that enable developers to use state and other React features without writing a class component. By using hooks like useState and useEffect, developers can manage state and perform side effects in functional components.




## Setting Up the Project

Before diving into the implementation, make sure you have a basic understanding of React and have Node.js and npm (Node Package Manager) installed on your system. Create a new React project using Create React App with the following command:

```
npx create-react-app localStorageExample

cd localStorageExample
```


Now, let's start by creating a new functional component that will showcase the usage of localStorage:


```
import React from 'react'


const LocalStorageExample = () => {
  // Your code will go here
};


export default LocalStorageExample;
```


## Using localStorage with React Hooks

To use localStorage with React Hooks, we'll use the useState hook to manage the state and the useEffect hook to interact with localStorage.




## Step 1: Import the necessary hooks and libraries

First, import the useState and useEffect hooks from React. We'll also create a simple form with an input field to demonstrate setting and getting items from localStorage:

```
import React, { useState, useEffect } from 'react'


const LocalStorageExample = () => {
  const [inputValue, setInputValue] = useState('');
  const [storedValue, setStoredValue] = useState('');


  useEffect(() => {
    // Your code will go here
  }, []);


  return (
    <div>
      <form>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button type="submit">Save to LocalStorage</button>
      </form>
      <div>
        <h2>Stored Value:</h2>
        <p>{storedValue}</p>
      </div>
    </div>
  );
};


export default LocalStorageExample;

```




## Step 2: Implement the useEffect hook

Now, let's implement the useEffect hook. This hook is responsible for two tasks:

1. Retrieving the stored value from localStorage when the component mounts.

2. Saving the input value to localStorage when the user submits the form.

```

import React, { useState, useEffect } from 'react'


const LocalStorageExample = () => {
  const [inputValue, setInputValue] = useState('');
  const [storedValue, setStoredValue] = useState('');


  useEffect(() => {
    // Get the value from localStorage when the component mounts
    const storedValue = localStorage.getItem('exampleData');
    if (storedValue) {
      setStoredValue(storedValue);
    }
  }, []);


  const handleSubmit = (e) => {
    e.preventDefault();
    // Save the input value to localStorage
    localStorage.setItem('exampleData', inputValue);
    setStoredValue(inputValue);
  };


  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button type="submit">Save to LocalStorage</button>
      </form>
      <div>
        <h2>Stored Value:</h2>
        <p>{storedValue}</p>
      </div>
    </div>
  );
};


export default LocalStorageExample;

```

## Testing the Implementation

Now that our component is ready, we can test it by running the React development server:

```
npm start

```

Open your browser and navigate to `http://localhost:3000/`  You should see the input field and a "Save to LocalStorage" button. Enter some text into the input field and click the button. The entered value will be stored in localStorage, and the "Stored Value" section will display the saved value.




## Conclusion

In this article, we've explored how to use localStorage with React Hooks to set and get items, allowing us to persist data locally within a React application. By combining the useState and useEffect hooks, we can efficiently manage state and interact with localStorage without the need for class components. Remember that localStorage has limitations, such as a maximum storage capacity and that the data is specific to a domain. In cases where you need more advanced state management or data sharing between different pages or components, you might consider other options like Redux or React's Context API. However, for simple local data persistence, localStorage with React Hooks provides an elegant and straightforward solution.