| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
- Props
- graphQL
- error
- 기준
- middleware
- useState
- REACT
- 삶
- web
- bitcoin
- Interface
- evm
- SSR
- hardhat
- CSS
- tailwindcss
- JavaScript
- CLASS
- concept
- nextJS
- API
- node.js
- express.js
- HTML
- typeScript
- blockchain
- solidity
- Ethereum
- Redux
- built in object
- Today
- Total
ReasonJun
React: useRef 본문
In React, the useRef hook is used to create a mutable reference that persists across renders. It provides a way to access and interact with DOM elements or values that may change over time without triggering a re-render of the component.
The useRef hook returns a mutable ref object with a .current property. This property can hold any value and remains the same between renders. When the .current value is updated, the component will not re-render.
Here are a few common use cases for useRef:
- Accessing DOM elements: You can use useRef to reference DOM elements and interact with them directly. For example, you can focus an input field or trigger other imperative actions on the DOM element.
- Storing values between renders: If you have a value that needs to persist between renders but doesn't affect the component's visual output, you can store it in a useRef value.
Here's an example that demonstrates how to use useRef to access a DOM element and store a value:
import React, { useRef, useEffect } from 'react';
const MyComponent = () => {
const inputRef = useRef(null);
const countRef = useRef(0);
useEffect(() => {
// Focus the input field on component mount
inputRef.current.focus();
}, []);
const handleClick = () => {
countRef.current += 1;
console.log('Button clicked', countRef.current);
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Click</button>
</div>
);
};
export default MyComponent;
By using useRef, you can access and store values that persist across renders without triggering re-renders of the component. This makes it useful for managing mutable values or interacting with DOM elements directly.
'Frontend > React' 카테고리의 다른 글
| React 18 : Suspense (0) | 2023.06.16 |
|---|---|
| React 18 : Automatic batching (0) | 2023.06.16 |
| React : debounce (0) | 2023.06.14 |
| React : Request AJAX within the component (two way) (0) | 2023.06.14 |
| React : React Router Dom APIs (Nested routing, Outlet, useOutletContext, index, useNavigate, useParams) (useLocation, useRoutes) (0) | 2023.06.14 |