skip to Main Content

I wanted to create a wrapper component and want to access some value from child’s component. I also don’t want to do any modification in existing child’s component code as it is being directly used at multiple places.

Is it advisable and not having any concerns regarding best practices?

function ParentComponent (props) {
  const childRef = React.useRef(null);
  React.useEffect(() => {
    if (childRef.current) {
      console.log("child's reference value", childRef.current.someValue);
    }
  }, []);
  return (<ChildComponent {...props } ref = {childRef}></ChildComponent>)
}

2

Answers


  1. Yes you can do this, although you probably shouldn’t.

    In most cases you would probably be better off with an onChange listener as prop for your component. Here is an example with a stateful child component and a parent listening to changes for that state.

    function Component({ onChange }) {
      const [str, setStr] = useState("");
      // run the effect again when the state changes
      useEffect(() => onChange?.(str), [str]);
      return <>{str}</>;
    }
    
    function Parent() {
      // this will be called each time the `str` state is updated
      const onChange = useCallback((str) => {
        console.log("child's reference value", str);
      }, []);
    
      return <Component onChange={onChange} />;
    }
    

    This is the go-to approach for what you are trying to achieve. Note that the reference objects are used to store a mutable values that do not cause a re-render when updated.

    Login or Signup to reply.
  2. This is fine as long as the child uses forwardRef, so that the ref is passed to the child component, and if there’s a useimperativehandle function to expose the said values.

    If not you have to implement forwardRef and useimperativehandle in the child component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search