Programming
EN
1 min read
Fix React Strict Mode renders twice in development
Sometimes, we want to run a snippet just once, even in development.

If React Strict Mode in development gets you into trouble in some cases, for example, you need a specific action to run only just once, but also don't want to lose the benefits of running the app in Strict Mode, I'll show you a way out!
First, you may need to check whether the environment your app is running on, like so:
tsx
process.env.NODE_ENV === 'development'
We need an indicator to determine which environment are we running on.
Then, in your component, create a counter state that helps us to detect which nth time that the component is rendered.
tsx
const [counter, setCounter] = useState(0);
Add a counter state into the component
Next, use useEffect clean up function to increase the counter!
tsx
useEffect(() => { return () => setCounter((c) => c + 1); }, []);
Increase the counter in the clean-up function of useEffect
Add a variable to check if we should do something, like so:
tsx
const shouldRunSomething = process.env.NODE_ENV === 'development' ? counter === 1 : true;
A variable to check if we should run the code
In this case, in development mode, the component always run twice, so we will run that code in the second time of component running.
For production, we don't have to check this counter.
Finally, use that variable to check if we should run or do something.
tsx
useEffect(() => { if (shouldRunSomething ) { // TO-DO } }, [shouldRunSomething]);
Use shouldRunSomething to only run the code in the second time.
To sum up, here's the full snippet:
tsx
const [counter, setCounter] = useState(0); const shouldRunSomething = process.env.NODE_ENV === 'development' ? counter === 1 : true; useEffect(() => { return () => setCounter((c) => c + 1); }, []); useEffect(() => { if (shouldRunSomething) { // TO-DO } }, [shouldRunSomething]);
The complete snippet
Hope this helps! Let me now if you have any comment.
