How to persist state on refresh with React?

Estimated read time 2 min read

In React, the state of a component is typically lost when the page is refreshed. However, you can persist the state of a component across refreshes by using the browser’s localStorage or sessionStorage API. Here’s an example of how to persist state on refresh with React:

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

function MyComponent() {
  const [count, setCount] = useState(() => {
    const storedCount = localStorage.getItem('count');
    return storedCount !== null ? parseInt(storedCount) : 0;
  });

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

  function handleClick() {
    setCount(prevCount => prevCount + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
      {/* rest of your component code */}
    </div>
  );
}

In this example, we define a component called MyComponent that uses the useState hook to keep track of the count state. We use the localStorage API to persist the count state across refreshes.

When initializing the count state, we use a function that reads the stored count value from localStorage. If there is no stored value, we default to 0.

In the useEffect hook, we use localStorage.setItem to store the current value of count whenever it changes. The second argument to useEffect is an array of dependencies that trigger the effect when they change. In this example, we only want to store the count value when it changes.

When the user clicks the button, we use the setCount method to update the count state. The setCount method takes a function that returns the new state value, which is the previous state value plus one.

By using localStorage to persist the state of a component, we can preserve the user’s data across refreshes and improve the user experience of our React app. Note that localStorage is limited to storing strings, so you may need to use JSON.stringify and JSON.parse to store and retrieve more complex state values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply