dkelsen / gatsby-blog-comments

This repo is used for utterances comments
0 stars 0 forks source link

call-child-function-from-parent-component-in-react/ #9

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

How To Call Child Function From Parent Component In React | Dilshan Kelsen

One way to call a child component's function from its parent is with the help of the useRef hook . Here's the gist of it: We pass a…

https://dilshankelsen.com/call-child-function-from-parent-component-in-react/

Terro216 commented 2 years ago

Thanks, nice example

avoajaugochukwu commented 2 years ago

Thank you Dilshan, this worked for me.

MarkMGill commented 2 years ago

Works great, thank you!

muammarFaiz commented 2 years ago

so it pass the alertUser function to parent using useEffect right? but what if alertUser try to access some variable from the child component? will it work and why?

GreatState commented 2 years ago

Does this work with React 18 best practices https://beta.reactjs.org/learn/synchronizing-with-effects#

?

dkelsen commented 1 year ago

@muammarFaiz In that case, you would need add alertuser to the dependency array of useEffect, otherwise the function instance assigned to childFunc.current will reference stale variables.