React/Velopert's React

[React] Study #11 | useRef ๋กœ ์ปดํฌ๋„ŒํŠธ ์•ˆ์˜ ๋ณ€์ˆ˜๋งŒ๋“ค๊ธฐ

yevdev 2021. 10. 4. 22:31

๐Ÿ’ก์ด์ „์˜ ref?

  • ํŠน์ • DOM์„ ์„ ํƒํ•ด์•ผํ•  ๋•Œ ์‚ฌ์šฉ 
  • ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ์—์„œ ์ด๋ฅผ ์„ค์ • ํ•  ๋•Œ useRef๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„ค์ •ํ•จ

 

๐Ÿ’กref์˜ ๋˜๋‹ค๋ฅธ ์šฉ๋„

  • ์ปดํฌ๋„ŒํŠธ ์•ˆ์—์„œ ์กฐํšŒ ๋ฐ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๋ณ€์ˆ˜๋ฅผ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์Œ
  • useRef๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๋ณ€์ˆ˜๋Š” ๊ฐ’์ด ๋ฐ”๋€๋‹ค๊ณ  ํ•ด์„œ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ฆฌ๋ Œ๋”๋ง ๋˜์ง€ ์•Š์Œ.
    • ๋ฆฌ์•กํŠธ ์ปดํฌ๋„ŒํŠธ์—์„œ์˜ ์ƒํƒœ๋Š” ์ƒํƒœ๋ฅผ ๋ฐ”๊พธ๋Š” ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๊ณ  ๋‚˜์„œ ๊ทธ ๋‹ค์Œ ๋ Œ๋”๋ง ์ดํ›„๋กœ ์—…๋ฐ์ดํŠธ ๋œ ์ƒํƒœ๋ฅผ ์กฐํšŒํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐ˜๋ฉด, useRef๋กœ ๊ด€๋ฆฌํ•˜๊ณ  ์žˆ๋Š” ๋ณ€์ˆ˜๋Š” ์„ค์ • ํ›„ ๋ฐ”๋กœ ์กฐํšŒ ๊ฐ€๋Šฅ
  • ์–ด๋–ค ๊ฐ’์„ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์„๊นŒ?
    • setTimeout, setInterval์„ ํ†ตํ•ด ๋งŒ๋“ค์–ด์ง„ id
    • ์™ธ๋ถ€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ƒ์„ฑ๋œ ์ธ์Šคํ„ด์Šค
    • scroll ์œ„์น˜

๐Ÿ’กํ•ด๋ณผ๊ฒƒ?

  • ๋ฐฐ์—ด์— ์ƒˆ ํ•ญ๋ชฉ์„ ์ถ”๊ฐ€ํ• ๋•Œ, ์ƒˆํ•ญ๋ชฉ์—์„œ ์‚ฌ์šฉํ•  ๊ณ ์œ  id๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ์šฉ๋„

1๏ธโƒฃ ๋ฐฐ์—ด์„ App ์—์„œ ์„ ์–ธํ•˜๊ณ  UserList ์—๊ฒŒ props๋กœ ์ „๋‹ฌ

App.js

import React from 'react'; 
import UserList from './UserList';

function App() {
  const users = [
    {name: 'John', age:19},
    {name: 'Car', age:20},
    {name: 'lee', age:14},
];
  return (   
      <UserList users={users}/>
  );
}

export default App;

UserList.js

import React from 'react'

function User({user}) {
    return(
        <div>
            <span>{user.name}</span>
            <span>{user.age}</span>
        </div>
    )
}

function UserList({users}) {

    return (
        <div>
            {/* ๋ฐฐ์—ด์„ ๋ Œ๋”๋งํ• ๋•Œ, key๋ผ๋Š” props๋ฅผ ์„ค์ •ํ•ด์ฃผ๊ธฐ!! */}
            {users.map(user => (
                <User user={user} key={user.id}/>
            ))}
        </div>
    )
}

export default UserList

 

2๏ธโƒฃ App ์—์„œ useRef()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ nextId ๋ผ๋Š” ๋ณ€์ˆ˜ ์ƒ์„ฑ

App.js

import React,{useRef} from 'react'; 
import UserList from './UserList';

function App() {
  const users = [
    {name: 'John', age:19},
    {name: 'Car', age:20},
    {name: 'lee', age:14},
];

const nextId = useRef(4);
const onCreate() => {
    // ๋‚˜์ค‘์— ๊ตฌํ˜„ ํ•  ๋ฐฐ์—ด์— ํ•ญ๋ชฉ ์ถ”๊ฐ€ํ•˜๋Š” ๋กœ์ง
    // ...

    nextId.current += 1;
};
  return (   
      <UserList users={users}/>
  );
}

export default App;
  • useRef()๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด, ์ด๊ฐ’์ด .current ๊ฐ’์˜ ๊ธฐ๋ณธ ๊ฐ’์ด ๋œ๋‹ค.
  • ์ด ๊ฐ’์„ ์ˆ˜์ •ํ•  ๋•Œ๋Š” .current ๊ฐ’์„ ์ˆ˜์ •ํ•˜๋ฉด ๋˜๊ณ  
  • ์กฐํšŒํ•  ๋•Œ๋„ .current ๊ฐ’์„ ์กฐํšŒํ•˜๋ฉด ๋œ๋‹ค.

 

 

 


Reference

https://react.vlpt.us/