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

Viewed 45

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

Try to remove <React.StrictMode> from your component.

As React docs says:

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions

Related