- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React useRef Hook
- useRef is a React hook that provides a way to persist values across renders without causing re-renders.
Purpose
- Retains values between renders without triggering a re-render.
- Commonly used for accessing and interacting with the DOM, storing mutable values, or persisting values across renders.
Syntax
- Import useRef from the 'react' library.
- Create a ref object using useRef().
import React, { useRef } from 'react';
const myRef = useRef(initialValue);
Accessing DOM Elements
- Use useRef to access and manipulate DOM elements.
import React, { useRef, useEffect } from 'react';
const DomManipulationExample = () => {
const inputRef = useRef(null);
useEffect(() => {
// Focus on the input element on mount
inputRef.current.focus();
}, []);
return (
<div>
<h2>Example: Accessing DOM Elements</h2>
<input ref={inputRef} type="text" placeholder="Type here" />
</div>
);
};
Persisting Values
- Use useRef to persist a value across renders without triggering re-renders.
import React, { useRef, useState } from 'react';
const PersistingValueExample = () => {
const renderCount = useRef(0);
// This component won't re-render when renderCount changes
const incrementRenderCount = () => {
renderCount.current += 1;
console.log('Render Count:', renderCount.current);
};
return (
<div>
<h2>Example: Persisting Values</h2>
<p>Render Count: {renderCount.current}</p>
<button onClick={incrementRenderCount}>Increment Render Count</button>
</div>
);
};
Storing Previous State
- Use useRef to store and access the previous state value.
import React, { useRef, useState, useEffect } from 'react';
const PreviousStateExample = () => {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
}, [count]);
return (
<div>
<h2>Example: Storing Previous State</h2>
<p>Current Count: {count}</p>
<p>Previous Count: {prevCountRef.current}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
</div>
);
};
Summary
useRef is a versatile hook that provides a way to persist values and interact with the DOM in a React component.