Passing the useEffect trigger to a Child component
posted 2022.02.15 by Clark Wilkins

A quick expansion on the last article:

Where this gets really useful is when you have a master list of objects that can be expanded into individual edit forms. What I have been doing is generating a summary view in a master component ListStuff, and passing the details of each item to a child EditStuff.

That's all well and good for updating in the context of EditStuff, but we need to get ListStuff to render again and show the updated state.

The trick turns out to be passing the useEffect() trigger down as a prop like this:

{Object.values( channelData ).map( (thisChannel, key ) => {

  const { manufacturer, modality } = thisChannel;

  return (

    <Accordion
      className="mt-3 mb-3"
      key={key}
    >

      <Accordion.Header>
        {manufacturersList[manufacturer]}, {modalitiesList[modality]} settings
      </Accordion.Header>

      <Accordion.Body>

        <EditChannel
          {...thisChannel}
          channelNumber={key + 1}
          setFetchChannels={setFetchChannels}
        />

      </Accordion.Body>

    </Accordion>

  );

} ) }

In the underlined section, I am passing the triggering function down to the child via props. Now, in the child, I can extract setFetchChannels, and use it upon a successful doSubmit() to trigger state in the parent component and re-render the DOM.