The additional hooks that you’ll be learning are useRef and useMemo.
useRef
The useRef function returns a mutable ref object and initializes its .current property to the passed argument. People often confuse the use of useRef hook with useState hook. You can instruct this hook to hold the reference of an HTML element. Using this reference, you can easily manipulate that element.
The useRef hook has only one property in it: .current. React does not re-render the page when its element changes. Nor does it re-render if you change the value of the .current property. Let’s understand the use of this hook with an example:
In the above code, the color of the input element changes according to the number you enter in the input box. First, it assigns the result from the useRef() hook to the count variable. There are two elements: input and the button. The input element has the value of the number and, the ref property of the input tag is count to match the variable.
When you click on the button, the checkNumber() function gets called. This function checks to see if the value of the number is greater than 10. It then sets the background color of the input element using the count.current.style.backgroundColor property.
useMemo
The useMemo hook will recompute a cached value when any of its dependencies change. This optimization helps to avoid expensive calculations on every render.
The syntax of the useMemo hook is as follows:
For better understanding, let’s consider an example. The code below toggles the colors of two headings. It calls the useState hook to keep track of their values. A function shows whether the color is hot or cold according to its value. Before returning the status of the colour, there is a while loop that pauses for approximately one second. This is for demonstration purposes, to explain the benefit of the useMemo hook.
When you click on toggleButton1, you should notice a slight delay while the state changes. Notice that there’s also a delay when you click on toggleButton2. But this should not happen, since the one-second pause occurs in displayColor. On this page, the buttons should be capable of acting independently. To achieve this, you can use the useMemo hook.
You need to wrap the displayColor function in the useMemo hook and pass color1 in the dependency array.
The useMemo hook takes a function and the dependencies as parameters. The useMemo hook will render only when one of its dependencies changes. It is useful in situations when you have to fetch from an API.
What to Do Next After Learning Hooks
Hooks are a very powerful feature and are commonly used in React projects. They provide a lot of potential for optimization. You can practice hooks by building small projects like forms or clock counters.
There are other advanced hooks like useReducer, useLayoutEffect, and useDebugValue. You can learn them by referring to the official React documentation.