Warning: Can’t perform a React state update on an unmounted component.
Many of you have ever worked with a condition based component render in React app, you will get warning(s) in your console:

Warning: Can’t perform a React state update on an unmounted component.

The most common cause of this warning is when a user sends an asynchronous request, but leaves the page before it completes or set state before component render and state is being used before initialized.
I especially wanted to know how to do this with hooks, because hooks are awesome.

I wanted to know how to avoid this classic React warning – here’s my solution.

const MyComponent = () => {

        const [counter, setCounter] = useState(0)

        const componentIsMounted = useRef(true)
        useEffect(() => {
            return () => {
                componentIsMounted.current = false
            }
        }, []) 

        const incrementCounter = useCallback(()=> {
            async () => {
                try {
                    await dbQuery()
                    if (componentIsMounted.current) {
                        setCounter(counter + 1)
                    }
                } catch (err) {
                    // Handle error
                }
            }
        }, [setCounter])

        render (
            <div>
                <button onClick={incrementCounter}>                       +
                </button>
                </div> 
        )
}
Spread the love
Last modified: November 27, 2019

Comments

Write a Reply or Comment

Your email address will not be published.