Search code examples
reactjs

Invoking child component from parent component


I am just starting with react, so please bear with me.

I have a parent react component, Users, which contains another react component like this:

<UsersTable onSelectRecord={onSelectRecord} />

'onSelectRecord' is a function defined in Users.

UseraTable is defined as:

const UsersTable = props => {...}

and its useEffect hook is implemented as:

useEffect(() => {
       fetchUsers(1);
}, [props.updateTime]);

What I understand from this is that useEffect hook is executed whenever updateTime property changes.

But in Users, I see no such property passed.

So how does it work?


Solution

  • Since updateTime isn't being passed as a prop to UsersTable, the useEffect will only run when the component mounts and not afterward because there's no change to updateTime.

    Here’s what’s happening:

    The useEffect in UsersTable depends on props.updateTime. It will run whenever updateTime changes.

    useEffect(() => {
        fetchUsers(1);
    }, [props.updateTime]);
    

    In the Users component, you're only passing onSelectRecord to UsersTable:

    <UsersTable onSelectRecord={onSelectRecord} />
    

    Since updateTime isn’t passed, props.updateTime is undefined. The useEffect will run once when the component mounts, but it won’t run again because undefined isn’t changing. If you want the useEffect to run based on updateTime, you need to pass it from Users. Otherwise, it will only run on the initial render.