Shantanu Tomar
Shantanu Tomar

Reputation: 1712

Using refs in React in stateful component

The question is aligned more towards the performance or best practices of implementation.

As per React Docs, refs, which are part of React16 can only be used in class-based(stateful) components. As stateless components do not have an instance or state we cannot have refs in the stateless component.

What is the tradeoff of changing the stateless component to stateful or class-based component to use refs? Is it a recommended approach OR if it's only about refs we can use the old native approach of document refs or Jquery of getting an element reference.

Will changing of stateless to stateful component just for using refs and not any of the lifecycle methods are considered as best practice?

Upvotes: 1

Views: 726

Answers (1)

etarhan
etarhan

Reputation: 4176

As far as I'm aware there is no real tradeoff when converting a stateless component to a stateful component, performance-wise at least (the following article outlines some findings with regards to this). Although you could go ahead an retrieve the DOM element by using document.getElementId or some other native solution, it is generally better to use refs since it's more inline with React's way of doing things (a more detailed Stack Overflow response and thread discussing this you can find here.

In case you are using refs to get an reference to DOM element when some kind of event is triggered, you could also retrieve the DOM node from the event itself without using any refs.

There is nothing forcing you to implement the life cycle hooks, even if you would convert your component to a class based one. Assuming the performance difference is minor it would be appropriate to convert a stateless functional component to a class based stateful component if you have an obvious use case where you want to use ref, although in most cases you could probably get away with using event handlers instead.

If you don't want to convert you functional component to a class based one, you could also use the useRef hook, which would allow you to use refs in your functional component without having to convert to a class based component (since React 16.8).

Upvotes: 1

Related Questions