How to use local storage in React.js?

by herminia_bruen , in category: Javascript , 6 months ago

How to use local storage in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 6 months ago

@herminia_bruen 

To use local storage in React.js, you can follow these steps:

  1. Import the useState hook from React:
1
import React, { useState } from 'react';


  1. Define a state variable to hold the data from local storage:
1
const [data, setData] = useState(localStorage.getItem('myData') || '');


In the example above, the data state variable is initialized with the value stored in the 'myData' key in local storage. If there is no value stored, an empty string is used as the initial value.

  1. Write a function to update the data and save it to local storage:
1
2
3
4
const updateData = (newValue) => {
  setData(newValue);
  localStorage.setItem('myData', newValue);
};


The updateData function takes a new value as input, updates the data state variable using setData, and then saves the new value to local storage using localStorage.setItem.

  1. Use the data state variable in your React components:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
return (
  <div>
    <input
      type="text"
      value={data}
      onChange={(e) => updateData(e.target.value)}
    />
    <p>{data}</p>
  </div>
);


In the example above, an input field is bound to the data state variable using the value attribute. When the input value changes, the updateData function is called to update the data state variable with the new value.


Note: Remember to import useState from React at the top of your file and to use the useState hook to declare the state variable.