const ref = useRef(initialValue)
Parameters
initialValue
- ref 객체의 'current' 속성이 초기에 가질 값.
- 초기 렌더링 이후에는 무시된다.
- 어떤 유형의 값이든 될 수 있다.
Returns
returns an objects with a single property:
current
- 처음에는 전달한 'initialValue'로 설정되어 있다.
- JSX 노드에 ref 속성으로 ref객체를 전달하면 React가 그것의 'current' 속성을 설정한다.
- 다음 렌더링에서는 'useRef'가 동일한 객체를 반환한다.
Usage
1. Referencing a value with a ref
by using ref, you ensure that:
- you can store information between re-renders (unlike regular variables, which reset on every rerender)
- changing it does not trigger re-render (unlike state variables) => not appropriate for information you want to display on the screen
- the information is local to each copy of your component(unlike variables outside, which are shared)
Difference between ref and state
ref | state |
returns {current: initialValue} | returns [value, setValue] |
doesn't trigger re-render when changed | trigger re-render when changed |
mutable can modify and update `current`'s value outside of the rendering process |
immutable must use the state setting function to modify state |
shouldn't read & wrte the `current` value during rendering | can read state at any time (each render has its own snapshot of state which does not change) |
Do not write or read ref.current
during rendering
function MyComponent() {
// ...
// 🚩 Don't write a ref during rendering
myRef.current = 123;
// ...
// 🚩 Don't read a ref during rendering
return <h1>{myOtherRef.current}</h1>;
}
instead, you can read or write refs from event handlers or effects
function MyComponent() {
// ...
useEffect(() => {
// ✅ You can read or write refs in effects
myRef.current = 123;
});
// ...
function handleClick() {
// ✅ You can read or write refs in event handlers
doSomething(myOtherRef.current);
}
// ...
}
if you have to read/write during rendering, use state instead.
2. Manipulating the DOM with a ref
First, declare ref object with an initial value of null
import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
// ...
then pass your ref onject as the ref attribute to the JSX of the DOM node you want to manipulate:
// ...
return <input ref={inputRef} />;
After React creates the DOM node and puts it on the screen, React will set the current property of your ref object to that DOM node. Now you can access the<input>
's DOM node and call methods like focus()
:
function handleClick() {
inputRef.current.focus();
}
React will set the current property back to null when the node is removed from the screen.
example of manipulating the DOM with useRef
Read more about manipulating the DOM with refs
3. Avoiding recreating the ref contents
function Video() {
const playerRef = useRef(new VideoPlayer());
// ...
even though the result of new VideoPlayer()
is only used for the initial render, it is still called on every render which can be wasteful.
to solve it,
function Video() {
const playerRef = useRef(null);
if (playerRef.current === null) {
playerRef.current = new VideoPlayer();
}
// ...
Normally, writing & reading ref.current
during render is not allowed. However, it's fine in this case because the result is always the same, ant the condition only executes during initialization so it's fully predictable.
How to avoid null checks when initializing useRef later
function Video() {
const playerRef = useRef(null);
function getPlayer() {
if (playerRef.current !== null) {
return playerRef.current;
}
const player = new VideoPlayer();
playerRef.current = player;
return player;
}
// ...
How to get a ref to a custom component
//this doesn't work
const inputRef = useRef(null);
return <MyInput ref={inputRef} />;
to fix this, find the component that you want to get a ref to and wrap it with forwardRef()
then the parent component can get a ref to it.
import { forwardRef } from 'react';
const MyInput = forwardRef(({ value, onChange }, ref) => {
return (
<input
value={value}
onChange={onChange}
ref={ref}
/>
);
});
export default MyInput;
Accessing another component's DOM nodes
참고
'FrontEnd > React' 카테고리의 다른 글
[ React ] useReducer (0) | 2024.01.15 |
---|---|
[ React ] useContext (0) | 2024.01.15 |
[ React ] imageURL 을 File instance 로 만들기 (0) | 2023.10.26 |
[ React ] Rendering Lists (feat. key ) (0) | 2023.10.24 |
[ React ] 컴포넌트 생명주기 (0) | 2023.10.24 |