Learn The useRef Hook in React
28 June, 2022
10
10
0
Contributors
useRef Hook
The useRef hook is similar to the useState hook, only that the useRef persists values upon render.
It is also used to access the DOM directly, i.e., it references the HTML element it’s being used in.
It can also be used to store a mutable value that does not cause a re-render when updated.
When using the useState hook, every change causes a re-render of the component it’s being used on, while the useRef hook persists value for every change and does not cause a re-render of the component.
Syntax
You can optionally initialize it with a default value by passing an argument to the hook.
useRef() returns only one item, which is an object called current.
Accessing The DOM Elements
We can access any attribute of the element we’re referencing, for example; let us focus on the input element
Let’s get data form a simple form with the useRef Hook
before submission
after submission
We write less code when we utilise the useRef hook instead of the useState hook to manage our data.