State Persistence

Tutorial 3 of 4

1. Introduction

Goal of the Tutorial

The main goal of this tutorial is to help you understand how to persist state in your React applications. State persistence is a critical aspect of frontend development that ensures data does not get lost when the page is refreshed or the browser is closed.

Learning Outcomes

By the end of this tutorial, you will be able to:

  • Understand what state persistence is and why it is necessary.
  • Implement state persistence in your React applications using different techniques.

Prerequisites

Before you start with this tutorial, you should have a basic understanding of:

  • HTML, CSS, and JavaScript
  • Basics of React (components, props, and state)

2. Step-by-Step Guide

State persistence involves saving the application's state to a storage that survives browser refreshes or closing, and retrieving this state when the application starts again. In React, this could be achieved using various methods including, but not limited to:

  • LocalStorage
  • SessionStorage
  • Cookies
  • IndexDB

Using LocalStorage

LocalStorage is a web storage that allows you to store data with no expiration time. The data will not be deleted when the browser is closed and will be available the next day, the next week, or even the next year unless it is manually cleared through settings or programatically.

Let's imagine we have a counter application:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;

If you refresh the page, the count will be reset to 0. To persist the count, we can use LocalStorage.

3. Code Examples

Example 1: Persisting State with LocalStorage

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

function Counter() {
  const [count, setCount] = useState(
    Number(localStorage.getItem('count')) || 0
  );

  useEffect(() => {
    localStorage.setItem('count', count);
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;

In the above code:

  • We initialize count with the value from localStorage (if it exists), or 0.
  • We use the useEffect hook to update localStorage whenever count changes.

4. Summary

In this tutorial, we've learned about state persistence and how to implement it using localStorage in React. The same concept can be applied to session storage, cookies, or IndexDB.

5. Practice Exercises

Exercise 1

Create a simple form that persists form data in localStorage. When the page is refreshed, the form fields should be populated with the saved values.

Exercise 2

Extend the Counter application to include a Reset button that resets the count to 0 and clears the localStorage.

Next Steps

To continue your learning, you can explore:

  • How to use sessionStorage, cookies, and IndexDB for state persistence
  • How to encrypt sensitive data before storing it
  • How to use third-party libraries, such as Redux Persist, to persist state

Additional Resources