Home   reactjs  

State in react is resetting after page is refreshed - How to prevent this?

In React, the state is kept in memory, so when the page is refreshed, the state is reset. To persist the state across page refreshes, you can use browser storage mechanisms like localStorage or sessionStorage.

Here are a few ways to achieve state persistence:

1. Using localStorage

localStorage allows you to store data in the browser that persists even after the browser window is closed. You can use it to save the state when it changes and load it when the component mounts.

Example: Persisting State with localStorage

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

const App = () => {
  // Initialize state with data from localStorage, if available
  const [value, setValue] = useState(() => {
    const savedValue = localStorage.getItem('myValue');
    return savedValue !== null ? JSON.parse(savedValue) : '';
  });

  // Save state to localStorage whenever it changes
  useEffect(() => {
    localStorage.setItem('myValue', JSON.stringify(value));
  }, [value]);

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <div>
      <input type="text" value={value} onChange={handleChange} />
      <p>Current value: {value}</p>
    </div>
  );
};

export default App;

2. Using sessionStorage

sessionStorage works similarly to localStorage, but the data is cleared when the page session ends (i.e., when the browser or tab is closed).

Example: Persisting State with sessionStorage

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

const App = () => {
  // Initialize state with data from sessionStorage, if available
  const [value, setValue] = useState(() => {
    const savedValue = sessionStorage.getItem('myValue');
    return savedValue !== null ? JSON.parse(savedValue) : '';
  });

  // Save state to sessionStorage whenever it changes
  useEffect(() => {
    sessionStorage.setItem('myValue', JSON.stringify(value));
  }, [value]);

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <div>
      <input type="text" value={value} onChange={handleChange} />
      <p>Current value: {value}</p>
    </div>
  );
};

export default App;

3. Using React Context with Persistent Storage

For more complex applications, you might want to manage persistent state across multiple components. You can use React Context along with localStorage or sessionStorage.

Example: Using Context to Manage Persistent State

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

// Create a context for the persistent state
const PersistentStateContext = createContext();

// Create a provider component
export const PersistentStateProvider = ({ children }) => {
  const [value, setValue] = useState(() => {
    const savedValue = localStorage.getItem('myValue');
    return savedValue !== null ? JSON.parse(savedValue) : '';
  });

  useEffect(() => {
    localStorage.setItem('myValue', JSON.stringify(value));
  }, [value]);

  return (
    <PersistentStateContext.Provider value={{ value, setValue }}>
      {children}
    </PersistentStateContext.Provider>
  );
};

// Create a custom hook to use the context
export const usePersistentState = () => {
  return useContext(PersistentStateContext);
};

// App component
const App = () => {
  const { value, setValue } = usePersistentState();

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <div>
      <input type="text" value={value} onChange={handleChange} />
      <p>Current value: {value}</p>
    </div>
  );
};

export default App;
Published on: Jul 04, 2024, 06:30 AM  
 

Comments

Add your comment