useRef

유관희·2022년 10월 21일
0

* 영상 출처: https://www.youtube.com/watch?v=VxqZrL4FLz8, https://www.youtube.com/watch?v=VxqZrL4FLz8&t=404s, https://www.youtube.com/watch?v=VxqZrL4FLz8&t=404s, https://www.youtube.com/watch?v=EMK8oUUwP5Qhttps://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/fa38e67b-6ad7-4eeb-b8a8-7d3b62e2ccd5.png(00:13)

https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/2fa8fd43-67e6-4e9b-81c8-cc7f74b2cd41.png(01:36)

https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/5a97a802-7bf6-4238-b2a1-c97c7cee9370.png(02:35)https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/f1a402aa-99a6-4cfb-ae4b-eadb6f088b30.png(04:21)https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/e3c525f3-5df2-4c05-8929-3d504f053075.png(06:09)
06
```
const increaseCountState = () => {
setCount (count + 1);
};
const increaseCountRef = () => {
countRef.current = countRef.current + 1;
};
return (
State: {count} Ref: {countRef.current} State Ref 2
) ```

p>useRef 에서는 Ref 올려 버튼을 계속 눌러도 카운터가 올라가지 않는다. 왜냐하면 useRef는 랜더링이 되지 않기 때문에 숫자는 계속 올라가고는 있으나 랜더링이 안되기 때문에 화면에 숫자는 올라가지를 않는다. 그대신 State 올려를 눌렀을 때 State 는 매번 랜더링이 되기 때문에 그재서야 랜더링이 되어서 그 때에 Ref 에 누적 되어 있는 숫자가 표시된다.

https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/3b0e076d-bc46-4a16-8765-460f53860e00.png(00:23)https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/1cf55efb-36be-43da-b894-46cfd5d082de.png(01:06)https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/0160f427-a6f0-41eb-97fe-4f59be18d33a.png(02:36)https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/ff87fe49-8b12-4c88-85de-6820d4b4cf12.png(03:18)https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/7e05b080-f39e-4989-acdd-b896899f4802.png(04:05)

input tag 에 ref ={inputRef} 를 하면 useRef 에 연결이 되었고 useEffect 에

inputRef.current.focus() 를 넣으면 랜더링 될때 input tag에 forcus 가 된다.

https://slid-users-assets-v1-seoul.s3.ap-northeast-2.amazonaws.com/public/capture_images/97cdb24fc99d46669aad77b743ae82eb/ac0172ef-6675-44c2-9d88-d8a3449b26ba.png(04:45)

Ref 값을 알기 위해서는 input tag ref 값을 넘겨주는데 inputRef.current.value 값이 속성이다.

alert 창이 닫힌 후 다시 input 에 focus 를 맞추기 위해서는 alert 밑에 inputRef.current.focus()

하면 된다.

profile
안녕하세요~

0개의 댓글