Last evening while looking into a popular react library, I came across ‘refs’ and even knowing it how it works i wasn’t quite convinced with my understanding so decided to dive more deeper into it and finally sharing my thoughts with you people.
According to react docs , refs are used to get reference to a DOM(Document Object Model) node or an instance of a component in a React Application i.e. refs would return the node we are referencing . Lets see it with an example .
In the above example for the getting the value of what bob is saying i am using target value of event e .Using refs it could have been done this way
Also, we can pass a callback in the refs which can be used to do other cool things. Using refs with callbacks above job could have been done this way
As we all know , ID’s works on a single element in whole DOM tree thus lets say we want to change the background-color on focus . With ID’s this will happen
As Bob comes before Tim and both have the same ID on which background manipulation code runs but only Bob gets angry on focus not Tim. If we use refs we can replace the IDs with the a particular ref name and we should be doing fine. But i would suggest using classes for use-case of this kind as its much better and also refs has its caveats which we would see soon.
If the ref points to a standard component (DOM node, such as
div etc) then to retrieve the element; you just need to call
If the ref points to a composite component (a custom component you have created yourself) you need to use the new
ReactDOM module like so
refvalue first set ?
Along with render() in react , lifecycle methods also exists like
So , the ref is first set after the first
render(), but before
According to official react docs ,
bind functions in a
render() produce a performance hit by creating a new function on EVERY re-render. It should be done something like this
Also If the
ref callback is defined as an inline function, it will get called twice during updates, first with
null and then again with the DOM element. React does this to “clean up” the old ref and “set up” the new ref just in case the previous and the next callbacks comes out to be truly different functions. And cleaning up is necessary to avoid stale references (and memory leaks).
According to official react docs , Although string refs are not deprecated, they are considered legacy, and will likely be deprecated at some point in the future. Callback refs are preferred.
As MyFunctionalComponent has no instances , above code won’t work as intended.
ref attribute will work inside a functional component as long as you refer to a DOM element or a class component:
Hope you now have a good understanding of refs along with it use-cases and caveats. If you find it useful do share it with other peeps around you.
Let’s continue the conversation on Twitter.