โœ”๏ธ React ๊ณต์‹๋ฌธ์„œ์—์„œ ์„ค๋ช…ํ•˜๋Š” useRef

  • useRef๋Š” .current ํ”„๋กœํผํ‹ฐ๋กœ ์ „๋‹ฌ๋œ ์ธ์ž(initialValue)๋กœ, ์ดˆ๊ธฐํ™”๋œ ๋ณ€๊ฒฝ ๊ฐ€๋Šฅํ•œ ref ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜.
  • ๋ณธ์งˆ์ ์œผ๋กœ useRef๋Š” .current ํ”„๋กœํผํ‹ฐ์— ๋ณ€๊ฒฝ ๊ฐ€๋Šฅํ•œ ๊ฐ’์„ ๋‹ด๊ณ  ์žˆ๋Š” โ€œ์ƒ์žโ€๋กœ์„œ, ๊ฐ์ฒด์ด๋‹ค.
    • useRef()๋Š” ์ˆœ์ˆ˜ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑ {current: ...}
  • useRef๋Š” ๋งค๋ฒˆ ๋ Œ๋”๋ง์„ ํ•  ๋•Œ ๋™์ผํ•œ ref ๊ฐ์ฒด๋ฅผ ์ œ๊ณต.
  • useRef๋Š” ๋‚ด์šฉ์ด ๋ณ€๊ฒฝ๋  ๋•Œ ์•Œ๋ ค์ฃผ์ง€ ์•Š์œผ๋ฉฐ, .current ํ”„๋กœํผํ‹ฐ๋ฅผ ๋ณ€ํ˜•ํ•˜๋Š” ๊ฒƒ์ด ๋ฆฌ๋ Œ๋”๋ง์„ ๋ฐœ์ƒ์‹œํ‚ค์ง€๋Š” ์•Š๋Š”๋‹ค.



โœ”๏ธ ์ •๋ฆฌํ•˜๋ฉด useRef๋Š”

  • ref๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด ๋‚ด๋Š” hook์ด๋ฉฐ
  • ref๋Š” render ๋ฉ”์„œ๋“œ์—์„œ ์ƒ์„ฑ๋œ DOM node๋‚˜ React Element์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•œ๋‹ค.
  • ref๋Š” ๋ณ€๊ฒฝ ๊ฐ€๋Šฅํ•œ ๊ฐ’์„ ๋‹ด๊ณ  ์žˆ๋Š” ๊ฐ์ฒด์ด๊ณ 
  • ์ด๋•Œ ref ๊ฐ์ฒด ์•ˆ์˜ ๊ฐ’์€ React์˜ ์ƒ๋ช…์ฃผ๊ธฐ์—์„œ ๋…๋ฆฝ์ ์ด๊ธฐ ๋•Œ๋ฌธ์—re-render์™€ ์ƒ๊ด€์—†์ด ๊ฐ’์ด ์œ ์ง€๋œ๋‹ค
  • ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜๋”๋ผ๋„ render ๋˜์ง€ ์•Š๊ณ , render ๋˜๋”๋ผ๋„ ๊ฐ’์ด ์œ ์ง€๋˜๋Š” ํŠน์ง•์„ ๊ฐ€์ง„๋‹ค


useRef ์‚ฌ์šฉ ์‚ฌ๋ก€

  1. ํŠน์ • DOM์— ์ ‘๊ทผํ•ด์•ผ ํ•  ๋•Œ
  • ํŠน์ • ์—˜๋ฆฌ๋จผํŠธ์˜ ํฌ๊ธฐ๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ
  • ์Šคํฌ๋กค๋ฐ” ์œ„์น˜ ๊ฐ€์ ธ์˜ค๊ธฐ ๋˜๋Š” ์„ค์ •
  • ์ธํ’‹๋ฐ•์Šค ํฌ์ปค์Šค ์„ค์ • ๋“ฑ
  1. ๋‹ค์‹œ ๋ Œ๋”๋ง ๋˜์–ด๋„ ๋™์ผํ•œ ์ฐธ์กฐ๊ฐ’์„ ์œ ์ง€ํ•  ๋•Œ
  • ์ผ๋ฐ˜ ๋ณ€์ˆ˜๋Š” ์žฌ ์„ ์–ธ๋˜๊ธฐ ๋•Œ๋ฌธ์— ์ดˆ๊ธฐํ™”๊ฐ€ ์ผ์–ด๋‚˜๊ณ 
  • state ๋˜ํ•œ ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜๋ฏ€๋กœ
  1. setInterval, setTimeout clear ํ•  ๋•Œ ๋“ฑ


:: ์ฝ”๋“œ ์˜ˆ์‹œ

  1. ๋‹ค์‹œ ๋ Œ๋”๋ง ๋˜์–ด๋„ ๋™์ผํ•œ ์ฐธ์กฐ๊ฐ’์„ ์œ ์ง€ํ•  ๋•Œ
  • state๊ฐ€ ๋ณ€ํ•˜๋”๋ผ๋„ render์— ์ƒ๊ด€์—†์ด ์œ ์ง€๋˜๋ฏ€๋กœ, state๊ฐ€ ๋ฐ”๋€Œ์–ด๋„ ref์•ˆ์˜ ๊ฐ’์€ 0์ด ์œ ์ง€
import React, { useEffect, useState, useRef } from 'react';

const Example = () =>{
  const [count, setCount] = useState(0);
  const countRef = useRef(count);

   useEffect(() => {
  	countRef.current = count;
   },[count])  // (1) ์ฒซ ๋ฒˆ์งธ useEffect

   useEffect(() => {
     return () => {
       console.log("unmount ์‹œ ์ถœ๋ ฅ", countRef.current);
     };
   }, []);     // (2) ๋‘ ๋ฒˆ์งธ useEffect

  return (
      <>
      	<h1>{count}</h1>
      	<button onClick={()=>setCount(c=>c+1)}>+<button/>
      </>
}



!! ์ฐธ๊ณ  ์ž๋ฃŒ