DEV Community

Kaziu
Kaziu

Posted on

<ChatGPT vs me> A better way to call functions in a child component from a parent component in React

❓Question

// should define in child component (<Body>) 
//   to follow the Container-Presenter pattern, but how?
const handleUpdate = useCallback(() => {
  hoge()
}, [])

return (
  <Body />
  <Footer>
    <Button onCliCk={handleUpdate} />
  <Footer />
)
Enter fullscreen mode Exit fullscreen mode

ChatGPT's answer

In this situation, ChatGPT might suggest using useRef and useImperativeHandle, which works, but there is a better way, I think.

That approach often adds complicated code, and some engineers may not be familiar with them

My answer

set a useState in parent component to store function states, and assign functions themselves in initial useEffect in child component

▼ Parent component

const [{handleUpdate, ....}, setHandlers] = useState({
  handleUpdate: undefined,
  hoge: undefined,
  .........
})

return (
  <Body setHandlers={setHandlers} />
  <Footer>
    <Button onCliCk={handleUpdate} />
  <Footer />
)
Enter fullscreen mode Exit fullscreen mode

▼ Child component <Body>

const onUpdate = useCallback(() => {
  update()
}, [])

useEffect(() => {
  setHandlers({
    handleUpdate: onUpdate,
    hoge: onHoge,
    .............
  })
},[])
Enter fullscreen mode Exit fullscreen mode

It would be simpler than using useRef and useImperativeHandle.
This pattern is kind of Function Injection

Your answer

what do you think?

Top comments (0)