ch-21 useRef Hook in React

13 May 2024

ch-21 useRef Hook in React

In React, the useRef hook provides a way to create a mutable reference that persists across renders. This reference can be used to interact with DOM elements directly or to persist values between renders without causing re-renders. Understanding how to use useRef effectively can be valuable for various tasks in React development.


Basic Usage


Creating a Ref

To create a ref, call the useRef hook:


import React, { useRef } from 'react';


const MyComponent = () => {

 const myRef = useRef(initialValue);

};


Accessing the Ref

You can access the current value of the ref using the current property:


console.log(myRef.current);


Updating the Ref

Updating the ref does not trigger a re-render:


myRef.current = newValue;


Common Use Cases


Referencing DOM Elements

The most common use case for useRef is accessing and manipulating DOM elements directly. This is useful for focusing inputs, measuring elements, or triggering imperative animations.


import React, { useRef, useEffect } from 'react';


const MyComponent = () => {

 const inputRef = useRef(null);


 useEffect(() => {

  inputRef.current.focus();

 }, []);


 return <input ref={inputRef} />;

};


Storing Previous Values

Another use case for useRef is storing values between renders without triggering a re-render. This is useful for preserving state across renders, such as previous props or state values.


import React, { useRef, useEffect } from 'react';


const MyComponent = ({ value }) => {

 const previousValueRef = useRef();


 useEffect(() => {

  previousValueRef.current = value;

 });


 const previousValue = previousValueRef.current;


 return <div>Previous value: {previousValue}</div>;

};


Avoiding Stale Closures

useRef can also help avoid stale closures in event handlers or asynchronous functions. By storing the current value of a variable in a ref, you can ensure that the value remains up-to-date even if the function is called asynchronously.


import React, { useState, useRef } from 'react';


const MyComponent = () => {

 const [count, setCount] = useState(0);

 const countRef = useRef(count);


 useEffect(() => {

  countRef.current = count;

 }, [count]);


 const handleClick = () => {

  setTimeout(() => {

   alert(`Count: ${countRef.current}`);

  }, 1000);

 };


 return (

  <div>

   <p>Count: {count}</p>

   <button onClick={() => setCount(count + 1)}>Increment</button>

   <button onClick={handleClick}>Show Count</button>

  </div>

 );

};


Conclusion

The useRef hook in React is a powerful tool for interacting with DOM elements, storing values between renders, and avoiding stale closures. By understanding its usage and common use cases, you can leverage useRef to enhance the functionality and performance of your React components. Whether you need to manipulate DOM elements, preserve state, or handle asynchronous operations, useRef provides a versatile solution for many scenarios in React development.

Notes and Source Code

Simple Empty
No data