Metgher Andrei
Metgher Andrei

Reputation: 217

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

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");
}, []);

Upvotes: 10

Views: 6579

Answers (2)

mbojko
mbojko

Reputation: 14689

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.

Upvotes: 0

Vipin N
Vipin N

Reputation: 43

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

Upvotes: 1

Related Questions