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