skip to Main Content

I have the following code:

const [number, setNumber] = useState(6)
function handleClick() { 
setNumber(5) 
}
...
<Button onClick={handleClick}/>

When I click the button, the component displays "5" as desired. But when I close the component and re-open it, it defaults back to "6". Does the set state happen on each re-render automatically? And is there a good way to work around this?

2

Answers


  1. The issue is using local state versus global state.

    To keep a global state, create a helperState.jsx (or .tsx) file with:

    // helperState.jsx
    export const [number, setNumber] = useState(6)
    

    then import it into your component:

    import { setNumber, number } from "./helperState.jsx"
    
    function handleClick() { 
      setNumber(5) 
    }
    
    // ...
    
    <Button onClick={handleClick}/>
    
    Login or Signup to reply.
  2. When you use useState in a functional component, the state is not preserved between renders by default. Each time the component is re-rendered, the state is reset to its initial value.

    The reason you see "5" when clicking the button is that the handleClick function updates the state with setNumber(5). This triggers a re-render, and since number is now set to 5, the component displays that value.

    However, when you close and re-open the component, it goes through the initial render again, and the useState hook sets number back to its initial value of 6.

    To work around this issue and have the state persist across re-renders, you can use a mechanism to store the state outside the component’s scope. One common approach is to use the browser’s localStorage to save and retrieve the value of number.
    Here’s how you can modify your code to achieve this:

    import React, { useState, useEffect } from 'react';
    
    function MyComponent() {
      // Retrieve the initial value from localStorage, or use 6 as the default value
      const initialValue = parseInt(localStorage.getItem('number')) || 6;
      const [number, setNumber] = useState(initialValue);
    
      useEffect(() => {
        // Save the current 'number' value to localStorage whenever it changes
        localStorage.setItem('number', number.toString());
      }, [number]);
    
      function handleClick() {
        setNumber(5);
      }
    
      return (
        <div>
          <p>{number}</p>
          <Button onClick={handleClick} />
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search