Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Create the same ref functionality in React Function component as in React Class component

I would like to create the exact same behaviour in function component ref as there is in class component ref.

Heres an example:

const AnotherComponent = () => {
    const DoSomething () => console.log(something);
    return <div> There is a content </div>;
}

const MyComponent () => {
    let newRef = useRef();
    useEffect(() => {
        newRef.current.DoSomething();
    }, []);
    return <AnotherComponent ref={newRef} />;
}

I know about forwardRef, but from what I understand it allows you to bind the ref to a specific input to get its events, but not to the WHOLE component with all its functions.

Is it even possible to achieve this with function components ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Yes, it's completely possible. React refs are for more than just getting access to DOMNodes. Use a combination of React.forwardRef and the useImperativeHandle React hook to forward a React ref to a function component and expose out functions/values.

const AnotherComponent = React.forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    doSomething
  }));
  const doSomething () => console.log(something);
  return <div> There is a content </div>;
});

...

const MyComponent () => {
  const newRef = useRef();
  useEffect(() => {
    newRef.current.doSomething();
  }, []);
  return <AnotherComponent ref={newRef} />;
}

Forwarding refs

forwardRef

useImperativeHandle

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!