useEffect dependency warning

Viewed 74

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

2 Answers

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.

This is the simplest solution

useEffect(() => { 
    async function myPageLoad() {
        ...
    }
    myPageLoad()
 }, []);
Related