Search code examples
reactjsreact-hooksuse-effect

How to use useEffect() inside a child component to fetch data?


I wonder if it make sense (or possible) to use useEffect inside a child component to load data only when the child component is included in the parent compnent.

Inside the child component I have the following code:

useEffect(() => {

    if (props.rubricItems.length < 1)
        props.fetchRubricsData(courseId);        

}, [])

But this does not trigger any call.

Do you suggest that I make fetch all data in the parent component? I did not want to do to avoid loading data that is not used. Any suggestions?


Solution

  • But this does not trigger any call.

    Why this happens?

    The reason why this happens is because you have an empty dependency array []. This means that it will only run when the component is mounted and never more (like componentDidMount). And because it only run one time, in that time, props.rubricItems.length < 1 is false.

    load data only when the child component is included in the parent compnent

    If you have some kind of logic that decides if you will render the child component, you could add a useEffect in the parent that will call that fetch.

    e.g.

    You render the component depending of some variable.

    { foo && <ChildComponent />}
    

    So you can add a useEffect that will run when foo value changes.

    useEffect(() => {
        if(foo){ // you can add you logic here
            // fetch the data
        }
    }, [foo]) // it will only run this when foo changes