Home > Blockchain >  Memory leak in useEffect Hook
Memory leak in useEffect Hook

Time:03-02

Warning : Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

useEffect hook: ` const [products, setProducts] = useState([]);

useEffect(() => {
    const getNewProducts = async () => {
        try {
            const res = await axiosInstance.get('/products?new');
                setProducts(res.data);
            // console.log(res)
        }catch(err) {
            console.log(err)
        }
    };
    getNewProducts();
});`

CodePudding user response:

Here is the solution ( recommended by React Developers/Docs ), and it worked for me to clean up the state on unmount.

    useEffect(() => {
        const getNewProducts = async () => {
            try {
                const res = await axiosInstance.get('/products?new');
                    setProducts(res.data);
                // console.log(res)
            }catch(err) {
                console.log(err)
            }
        };
        getNewProducts();

        return () => {
        setProducts([])
        }
    });`

CodePudding user response:

If you do not want to run getNewProducts every single time when your component is re-rendered, you can pass an empty array as a second parameter to the useEffect hook. The common way to clean up the useEffect hook is just to return a function in it. That function will be called automatically when the component will be unmounted.

useEffect(() => {
   // your code goes here ...

   return () => { // clean up process goes here ...  }
}, [])
  • Related