0% found this document useful (0 votes)
3 views

React Useref Tutorial

userf

Uploaded by

suchit kapale
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

React Useref Tutorial

userf

Uploaded by

suchit kapale
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Understanding useRef Hook in React

The useRef hook in React is a versatile tool that allows developers to persist values across
renders, interact with the DOM, and manage mutable state without causing a re-render.
Below are multiple ways useRef can be utilized in different scenarios.

1. Accessing and Manipulating DOM Elements


useRef can be used to access a DOM element and manipulate it directly without triggering
re-renders. This is useful for focusing inputs, modifying element styles, and more.

Example:

const inputRef = useRef(null);

const handleFocus = () => {


inputRef.current.focus();
};

<input ref={inputRef} type="text" />


<button onClick={handleFocus}>Focus Input</button>

2. Storing Mutable Values That Persist Across Renders


useRef can store values that persist across renders without causing re-renders. This is
commonly used for timers and interval IDs.

Example:

const timerRef = useRef(null);

const startTimer = () => {


timerRef.current = setInterval(() => setCount((prev) => prev + 1),
1000);
};

const stopTimer = () => {


clearInterval(timerRef.current);
};
3. Maintaining Previous Values or State Across Renders
You can use useRef to store the previous value of a state and access it later, without causing
any re-renders.

Example:

const prevCountRef = useRef();

useEffect(() => {
prevCountRef.current = count;
}, [count]);

const prevCount = prevCountRef.current;

You might also like