šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Catching errors with the double call of useEffect in React StrictMode

One thing that React StrictMode does is to mount, unmount, and mount again each component. The reason for this is to test that the components we create are robust and work as expected.

While the extra mountain and unmounting determine a double call of useEffect(), you should not worry about the performance issues given that React Strict Mode is meant to run only in development mode, not in real production environments.

For example, take the below component:

const BrokenTimer = () => {
    const [counter, setCounter] = useState(0)
    useEffect(() => {
        setInterval(() => setCounter(c => c + 1), 1000)
    }, [])

    return (<div> āŒ Broken Timer: {counter} </div>)
}

While everything may look and work as expected on the first run, this component will break if we unmount it and mount it back again. The reason for this is we don't clear the interval when unmounting.
Catching errors with the double call of useEffect of React StrictMode

This is especially useful when working with things such as debounced calls of useEffect() in React.

On the other side let's see the correct implementation of the timer:

const GoodTimer = ()=> {
    const [counter, setCounter] = useState(0)
    useEffect(() => {
        let int = setInterval(() => setCounter(c => c + 1), 1000)
        return () => clearInterval(int)
    }, [])

    return (<div> šŸ‘ Good Timer: {counter} </div>)
}

If we run these two components side by side, using the StrictMode, the bug will become obvious:

<StrictMode>
    <BrokenTimer/>
    <GoodTimer/>
</StrictMode>

Catching errors with the double call of useEffect of React StrictMode

You can check out the full code here and run the example Github pages here.

In conclusion, while the double call of useEffect() during the remount cycle in React StrictMode may initially seem like an inconvenience, I hope this example illustrates how valuable the StrictMode can be for identifying potential bugs in component implementations.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *