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
The issue is using local state versus global state.
To keep a global state, create a
helperState.jsx
(or.tsx
) file with:then import it into your component:
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: