How to handle data persistence in React application
Data persistence is a crucial aspect of building robust and reliable web applications. In a React application, there are various techniques and tools available to handle data persistence effectively.
What is data persistence?
Data persistence refers to the ability of an application to store and retrieve data across different sessions or interactions. It ensures that data remains available and secure, even when the application is closed or refreshed, by using techniques such as local storage, session storage, cookies, or server-side storage.
In this Answer, we will explore some of the common approaches for handling data persistence effectively.
Local storage
One of the simplest ways to persist data in a React application is by utilizing the browser's local storage. Local storage allows storing key-value pairs in the user's browser, which can be accessed even after the browser is closed and reopened.
Example
// Saving data to local storagelocalStorage.setItem('key', JSON.stringify(data));// Retrieving data from local storageconst storedData = localStorage.getItem('key');const parsedData = JSON.parse(storedData);
Explanation
Line 2: It stores the
dataobject as a JSON string in the browser's local storage with the key'key'.Lines 5–6: To retrieve the data,
localStorage.getItem('key')is used to get the stored string, andJSON.parse(storedData)converts it back to its original format, storing it in theparsedDatavariable.
Implementation
Session storage
Similar to local storage, session storage provides a way to store data in the user's browser. However, the data stored in session storage is only available for the duration of the browser session. Once the browser is closed, the data is cleared.
Example
// Saving data to session storagesessionStorage.setItem('key', JSON.stringify(data));// Retrieving data from session storageconst storedData = sessionStorage.getItem('key');const parsedData = JSON.parse(storedData);
Explanation
Line 2: It stores the
dataobject as a JSON string in the browser's session storage with the key'key'.Lines 5–6: To retrieve the data,
sessionStorage.getItem('key')is used to get the stored string, andJSON.parse(storedData)converts it back to its original format, storing it in theparsedDatavariable.
Implementation
Cookies
Cookies are another common method for data persistence. They are small text files stored in the user's browser and sent with each request to the server. React applications can use cookies to store and retrieve data. There are various libraries available for managing cookies in React, such as js-cookie or react-cookie.
Example
// Setting a cookieimport Cookies from 'js-cookie';Cookies.set('key', JSON.stringify(data));// Retrieving a cookieconst storedData = Cookies.get('key');const parsedData = JSON.parse(storedData);
Explanation
You will need to install js-cookie library to run this. To install js-cookie, run the following command:
npm i js-cookie
Line 4: In this line, the code
Cookies.set('key', JSON.stringify(data))sets a cookie with the key'key'and stores thedataobject as a JSON string.Lines 7–8: To retrieve the data,
Cookies.get('key')is used to get the stored cookie value, andJSON.parse(storedData)is used to convert the retrieved string back to its original format, storing it in theparsedDatavariable.
Implementation
import React, { useState, useEffect } from 'react';
import { useCookies } from 'react-cookie';
const Form = () => {
const [name, setName] = useState('');
const [cookies, setCookie] = useCookies(['name']);
useEffect(() => {
const storedName = cookies.name;
if (storedName) {
setName(storedName);
}
}, [cookies]);
const handleChange = (e) => {
setName(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
setCookie('name', name, { path: '/' });
};
return (
<div>
<h1>Cookies Example</h1>
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={handleChange} placeholder="Enter your name" />
<button type="submit">Save</button>
</form>
<p>Hello, {name || 'Stranger'}!</p>
</div>
);
};
export default Form;
Server-side persistence
To store data on the server side, using a database or other storage solutions, your application communicates with an API to send and retrieve data. You can use various libraries like Axios or the built-in Fetch API to make HTTP requests.
Example
// Saving data to the serverimport axios from 'axios';axios.post('/api/data', data).then(response => {console.log(response.data);}).catch(error => {console.error(error);});// Retrieving data from the serveraxios.get('/api/data').then(response => {const data = response.data;// Process the retrieved data}).catch(error => {console.error(error);});
Explanation
You will need to install axios library to run this. To install axios, run the following command:
npm i axios
Lines 4–10: In this line, the code
axios.post('/api/data', data)sends a POST request to the server endpoint/api/datawith thedataobject as the payload. The response data is logged to the console.Lines 13–20: To retrieve data from the server,
axios.get('/api/data')sends a GET request to the server endpoint/api/data. The response data is then stored in theresponse.datavariable and can be processed accordingly.
Implementation
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const TodoList = () => {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState('');
useEffect(() => {
fetchTodos();
}, []);
const fetchTodos = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/todos');
setTodos(response.data);
} catch (error) {
console.error('Error fetching todos:', error);
}
};
const addTodo = async () => {
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/todos', {
title: newTodo,
completed: false,
});
setTodos([...todos, response.data]);
setNewTodo('');
} catch (error) {
console.error('Error adding todo:', error);
}
};
const handleInputChange = (e) => {
setNewTodo(e.target.value);
};
return (
<div>
<h1>Todo List</h1>
<input type="text" value={newTodo} onChange={handleInputChange} placeholder="Enter a new todo" />
<button onClick={addTodo}>Add Todo</button>
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</div>
);
};
export default TodoList;
State management libraries
In larger React applications, you may need to manage complex states across multiple components. State management libraries like Redux or MobX can help in handling data persistence by providing a central store for managing application data.
Conclusion
We explored several techniques for handling data persistence in a React application. By understanding these techniques and using them appropriately, we can build React applications that persist data reliably and provide a seamless user experience.
Cookies | Local Storage | Session Storage | |
Accessibility | Any window | Any window | Same tab |
Storage Location | Browser and server | Browser only | Browser only |
Free Resources