Search code examples
reactjsreact-nativeuse-effect

useEffect dependency warning


I am working on a reactjs web application.

Here is my code source:

import React, { useContext, useState, useEffect } from "react";

...

function myPage() {
    async function myPageLoad() {
        ...
    }

    useEffect(() => { myPageLoad(); }, []);


    return (<div>My page content</div>);
}

export default myPage;

I want myPageLoad to be called when the page is displayed (initialization). Please note i will also call this function when i want to refresh my page's informations.

Can you confirm me useEffect is the good way to call myPageLoad function ? Or is there another way to do that ?

It seems to work but i get this warning at runtime:

React Hook useEffect has a missing dependency: 'myPageLoad'. Either include it or remove the dependency array react-hooks/exhaustive-deps

I have tried to put myPageLoad in dependency array but it does not work.

Any idea ?

Thanks


Solution

  • To do this, you have to update your myPageLoad function as useCallback function:

    const myPageLoad = useCallback(async () => {
       ...
    }, []);
    
    useEffect(() => {
      myPageLoad();
    }, [myPageLoad]); 
    

    This guarantees that the myPageLoad function identity is stable and won’t change on any re-renders.