React hooks are widely used throughout the globe. Despite the ease and comfort that they offer, hooks are often mis/partially understood and implemented poorly, resulting in poor quality code. useState and useRef are two of the most used/confused hooks. Let’s declutter them.
useState hook enables us to create a state variable of a component. This state variable holds dynamic data which has the ability to change as per user’s interaction. It takes a parameter (the initial value) and returns an array consisting of a variable (state) and a function to mutate that variable (stateUpdater).
Following is an example of it’s initialization:
[React] const [count, setCount]=useState(0); //count is the name of the variable. //setCount is the name of the function to modify value of count. //Any name could be used for the variable and the function modifying it. //0 is the value count is initialized with. [React]useRef hook empowers us with a way to manipulate DOM elements directly. It takes a parameter (the initial value ) and returns a mutable ref object whose .current property is initialized to the initial value.
Following is an example of it’s initialization:
[React] const elementRef=useRef(0); //elementRef is the name of the ref to be created. //Any name could be used for the variable and the function modifying it. //0 is the value count is initialized with. [React]Too much theory, let’s see some example and grasp it better.
In the above examples we have created an input field, and a submit button to hold the response filled. As is evident from the above examples, useState causes the component to re render each time the input is modified, but useRef doesn’t. In the examples employed, we have taken a single component with just handful elements which would not make a noticeable difference. However, in real world scenarios, the app may consists of numerous children, which further have children. In such cases, re rendering a parent component is a very expensive DOM manipulation. Hence, further denting the performance of the application.