Using useRef As useState Replacement — Here Is When and Why
The useState
hook is probably the go-to hook for anything, related to saving data in React.js. Yet, it is not always the best choice. On the other hand, is the useRef
hook. Sadly, the latter one is often only associated with DOM elements. The reality is different: useState, as well as useRef, can be used very well for state-related things and even complement each other. Here is why.
The problem with useState
To make it quick: The benefit of useState is also its disadvantage. Well, at least sometimes. The cool thing about state in React is, that whenever we change it, the change is visible in the DOM. Just think about a basic counter-example, using useState, and how the number displayed changes whenever we click a button.
This is cool. But not for free.
We can see this in a small code example:
Whenever we type something into the input field, in the console the message “rerender” appears. (Let’s ignore the possible value attribute of the input for now). This is…