Can I keep <StrictMode> in my app but make it not render twice
Asked Answered
G

2

10

I have my app inside a Strict Mode and it makes it difficult to run with my useEffect(). It basically logs all my values twice in the console which is not the result I want to achieve.

 useEffect(() => {
console.log('logs some data')
}, []);

It there a way to make useEffect only show the data once and keep the StrictMode inside my app component?

root.render(
<React.StrictMode>
 <App />
</React.StrictMode>
);

I did try using the useRef method but I was advised by my staff to not use this specific method and try another possible outwork.


Solution: If you ever need to keep Strict Mode in your component but need to make your useEffect no render twice, you could use useRef :

Example:

 let shouldlog = useRef(true);

 useEffect(() => {
 if (shouldlog.current) {
  shouldlog.current = false;
  console.log("component mounted");
  }

return () => console.log("function cleaned up");
}, []);
Grebe answered 20/7, 2022 at 9:35 Comment(2)
no you can't: beta.reactjs.org/learn/…, but you can use ref approach if none of the scenarios work for you in that linkCurcuma
The double rendering (or render - unmount - render) is there to help people spot problems in their useEffects. But it's not doing this in production mode. My guess is that the React team wants to prepare people for future versions of React, where abusing useEffect will cause problemsEnrica
M
1

We have to understand the concept of Strict mode first then only we will react the solution

<StrictMode> helps find common bugs in your components early during development.

Reference

Strict Mode enables the following development-only behaviors:

  1. Your components will re-render an extra time to find bugs caused by impure rendering.
  2. Your components will re-run Effects an extra time to find bugs caused by missing Effect cleanup.
  3. Your components will be checked for usage of deprecated APIs.

So basically is used to find the common errors or bugs during the development to build a quality React app

Marinate answered 12/6, 2023 at 13:24 Comment(0)
F
0

You can take advantage of the cleanup function to cancel the redundant work, for example using a 0 timeout:

  useEffect(() => {
    const timeout = setTimeout(() => {
        console.log('one console log ' + new Date().valueOf(); 
    }, 0);
    
    return () => {
        clearTimeout(timeout);
    }
  }, []);

The life cycle looks roughly: create component, immediately destroy it, create it again. And with effect: run effect, immediately run its cleanup function, run it again.

Fence answered 12/6, 2023 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.