DEV Community

loading...

Discussion on: Understanding the use of useRef hook & forwardRef in React

Collapse
lukeshiru profile image
LUKESHIRU

One thing you can do, is put everything on an util to reuse it in every component:

import { forwardRef } from "react";

export const withRef = (displayName, component) =>
    Object.assign(
        forwardRef((props, ref) =>
            component({ ...props, ref })
        ),
        { displayName }
    );
Enter fullscreen mode Exit fullscreen mode

And then you can use it with any component:

const Input = withRef("Input", props => (
    <input {...props} />
));
Enter fullscreen mode Exit fullscreen mode

We take displayName as an argument to make the experience with React DevTools a little better, and we send props and ref together so we can just spread props naturally.

You can also use preact, which doesn't need this kind of stuff, because the ref is always forwarded :D

Collapse
sajithpradeep profile image
Sajith Pradeep Author

Thanks for bringing in this perspective. I will try this out. It makes more sense as there are multiple instances where forwarding the hooks is required and this helps us stick to the DRY principle.

Collapse
karem1986 profile image
Karem

could u please explain what is the DRY principle? and if you have the link to test the code from github that would be awesome please :)

Thread Thread
lukeshiru profile image
LUKESHIRU

The DRY principle is just an acronym for "Don't Repeat Yourself". Basically is to avoid having code duplication by moving some logic into reusable functions. In this particular scenario, having a function like withRef helps with DRY because we don't need to write that logic every time we have a component like that, we just call the withRef function and done :)

Thread Thread
karem1986 profile image
Karem

Thank you!