Skip to content

Commit

Permalink
clarify strictmode in side effects
Browse files Browse the repository at this point in the history
  • Loading branch information
amothm80 committed Dec 12, 2024
1 parent ab056cf commit 8b2b1fa
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion react/states_and_effects/how_to_deal_with_side_effects.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ useEffect(() => {

Oh, it's not going berserk anymore! We still have an issue with the counter updating twice every second though. That can be understood as a [behavior caused by the React StrictMode](https://react.dev/reference/react/StrictMode#strictmode). It is supposed to help us catch bugs, so what is that bug here?

With `StrictMode`, `App` is mounted, unmounted, then mounted again. This behaviour of `StrictMode` is only in the development environment. Notice that every time the `useEffect` hook runs, a new `setInterval` is used. When the component is unmounted the first time, `setInterval` is not stopped, it keeps incrementing. This unnecessary behavior can be prevented by clearing the interval when the component is unmounted and that is where the third part of our `useEffect` hook comes in - the cleanup function.
With `StrictMode`, the `App` component is mounted, unmounted, then mounted again. This behaviour of `StrictMode` is only in the development environment. Notice that every time the `useEffect` hook runs, a new `setInterval` is used. When the component is unmounted the first time, `setInterval` is not stopped, it keeps incrementing. This unnecessary behavior can be prevented by clearing the interval when the component is unmounted and that is where the third part of our `useEffect` hook comes in - the cleanup function.

You can return a function from the callback in the `useEffect` hook, which will be executed each time before the next effect is run, and one final time when the component is unmounted. In this case, let us clean up the interval with a cleanup function.

Expand Down

0 comments on commit 8b2b1fa

Please sign in to comment.