0
 App [4] | ___________________________________ | | Child1 [3] Child2 [5] | | Child1a [2] function displayProperty() [6] | function onSetProperty() [1] 

I'm just beginning to learn React and trying to understand the built-in communication channels between components without using Redux state management. Can anyone provide a bit of guidance on a best practice when calling functions on child components?

My current approach with useRef and useImperativeMethods works but I'm not sure if this is a best practice because the docs state "As always, imperative code using refs can/should be avoided in most cases."

Is this one of those cases where a forwardRef with useImperativeMethods should be used?

Current program flow is:

  • Set property value in Child1a component
  • The onSetProperty event is bubbled up though Child1a => Child1 => App
  • The App component contains a variable 'const child2Ref = useRef()'
  • Child2 is defined as:

    const Child2 = forwardRef((props, ref) => { useImperativeMethods(ref, () => ({ displayPropertyOption(value) { console.log(The value is ${value}); } } ));

https://reactjs.org/docs/hooks-reference.html#useimperativemethods

1
  • 1
    Step one in building a UI with React is to never, ever, call "functions" on a descendant. Your parent component should really only care about its direct child components, and regulate their behaviour by updating props. If you need to call their API functions, you're mixing models in a way that will likely cause confusion for yourself and anyone else who has to work on your code. Got data for somewhere downstream? Hand it off, and keep doing so until it hits the right component. Or use a data manager/router (e.g. light via shared manager, super-heavy via redux, etc) Commented Jan 13, 2019 at 20:11

1 Answer 1

0

You always want to have your state at the highest needed/possible component level. To modify that state or display it in a child component, you pass the state variable and the function (which modifies that state) itself to the child component which calls the given function.

Sign up to request clarification or add additional context in comments.

Comments