— React, localStorage, JavaScript — 1 min read
localStorage is a browser-based storage mechanism that persists data even after the browser is closed. It’s ideal for storing small amounts of data that your application needs to access quickly. In this article, we'll explore how to use localStorage effectively with React.
Before diving into React, let’s quickly review localStorage basics:
To save data to localStorage in React, we can utilize the useEffect
hook to update localStorage whenever the data changes. Here's a basic example:
1import { useState, useEffect } from 'react';2
3function MyComponent() {4 const [data, setData] = useState('');5
6 useEffect(() => {7 localStorage.setItem('myData', data);8 }, [data]);9
10 return (11 <input type="text" value={data} onChange={(e) => setData(e.target.value)} />12 );13}
In this example:
data
.useEffect
hook runs whenever data
changes.useEffect
, we store the data
to localStorage using the key myData
.To retrieve data from localStorage, we can use the getItem
method and parse the retrieved string if necessary. Let's modify the previous example to fetch data from localStorage on component mount:
1import { useState, useEffect } from 'react';2
3function MyComponent() {4 const [data, setData] = useState('');5
6 useEffect(() => {7 const savedData = localStorage.getItem('myData');8 if (savedData !== null) {9 setData(savedData);10 }11 }, []);12
13 useEffect(() => {14 localStorage.setItem('myData', data);15 }, [data]);16
17 return (18 <input type="text" value={data} onChange={(e) => setData(e.target.value)} />19 );20}
Here, we added a second useEffect
hook with an empty dependency array. This hook runs only once when the component mounts. It retrieves the data from localStorage using getItem
, parses it if needed (in this case, no parsing is required), and updates the data
state.
Remember, localStorage only stores strings. To store complex data types like objects or arrays, you need to stringify them before saving and parse them when retrieving:
1import { useState, useEffect } from 'react';2
3function MyComponent() {4 const [data, setData] = useState([]);5
6 useEffect(() => {7 const savedData = localStorage.getItem('myData');8 if (savedData !== null) {9 setData(JSON.parse(savedData));10 }11 }, []);12
13 useEffect(() => {14 localStorage.setItem('myData', JSON.stringify(data));15 }, [data]);16
17 // ...18}