The useRef hook in React allows you to create a mutable value that persists across renders of a functional component. It provides a way to access and interact with DOM elements or any other mutable value without triggering a re-render.
Here's the basic syntax of the useRef hook:
To use useRef, you can follow these steps:
1. Create a Ref
Use the useRef hook to create a ref object. You can optionally provide an initial value to the useRef function.
2. Access the Ref
You can access the current value of the ref using the .current property of the ref object. The initial value passed to useRef will be available as the initial value of .current.
In the example above, the useRef hook is used to create a inputRef ref object. The ref is then attached to an <input> element using the ref prop. When the button is clicked, the handleClick function is called, and it uses the inputRef.current to access the DOM node and call the focus() method to focus the input element.
3. Persistence across Renders
The value of the ref persists across renders of the component, and updating the ref value does not cause a re-render. You can update the ref value by assigning a new value to ref.current.
In this example, the counterRef ref object is created with an initial value of 0. Inside the useEffect hook, the value of the ref is updated by incrementing counterRef.current. Since updating the ref value doesn't trigger a re-render, the component will only render once, and the value of the counter will increment with each render of the effect.
The useRef hook is useful for various scenarios, such as accessing DOM elements, storing mutable values, or caching values that need to persist across renders without causing re-renders.
Remember to import the useRef hook from the React module.
Yes, you can access the current value of a ref using ref.current. The current property holds the current value of the ref, and you can read or modify it directly.
Yes, you can use multiple useRef Hooks in a single component to create multiple refs for different DOM elements or values.
Yes, the useRef Hook can be used to manage form inputs by creating a ref for each input element. You can then access the input values and perform actions like focus or validation programmatically.