5

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?

Flip
  • 6,233
  • 7
  • 46
  • 75
renakre
  • 8,001
  • 5
  • 46
  • 99

1 Answers1

6

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
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • 1
    Thanks for the answer! Then in general it is a good practice (or the only practice) not to leave fetching data to child components. Do you agree? – renakre Jul 26 '19 at 12:16
  • @renakre It depends, but why would you want to fetch the data in the child component? – Vencovsky Jul 26 '19 at 12:23
  • 1
    It was to fetch it when only child is loaded. But, as you mentioned in your answer, this can be controlled from the parent. So, I guess apart from exceptions, this is how to do it – renakre Jul 26 '19 at 12:25
  • I want to fetch **in** the child component because the button is in the child component. I want to do the api request in the component that has the button, not the parent. – jack blank Oct 23 '19 at 08:36