Let's assume that you want to save the current state of a React component and recover it after going back to the previous page.
If you don't want to store the state locally, you can create a component to save the current state.
Example:
javascriptconst state = {}; /* * Saves the state of a component * @param {component} Name of the component to store the state * @param {object} Object to store */ export const saveState = (component, object) => { state[component] = object; } /* * Returns the state of a component * @returns {object} Object stored */ export const getState = (component) => { return state[component]; }
Now, let's assume a component that counts clicks and whose state you want to save:
jsximport React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; import { getState, saveState } from './StateSaver'; const Test = () => { const [numClicks, setNumClicks] = useState(0); useEffect(() => { // Checking if there is a state saved // On first render // Setting state variables if so if(getState('Test')){ // At this point you can get the saved state of the variables let { numClicks } = getState('Test'); // Recovering the old state setNumClicks(numClicks); } }, []); useEffect(() => { // Saving the state when the current state changes saveState('Test', { numClicks: numClicks }); }, [numClicks]); return( <div> <p>The number of times you clicked on a button is {numClicks}.</p> <button onClick = {() => setNumClicks(numClicks + 1)}>Click me</button> <Link to = '/'>Go to main page</Link> </div> ); } export default Test;
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.