[Hook] useCallback

๊ฐ•์€๋น„ยท2022๋…„ 1์›” 12์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
13/36

react ์Šคํ„ฐ๋””์—์„œ ๋ฆฌ์•กํŠธ๋ฅผ ๋‹ค๋ฃจ๋Š” ๊ธฐ์ˆ ์ด๋ผ๋Š” ์ฑ…์„ ์„ ์ •ํ–ˆ๊ณ  ์ด ์ฑ…์„ ์ฝ๊ณ  ๋ฐฐ์šด ๊ฒƒ์„ ๋ฐ”ํƒ•์œผ๋กœ ์ž‘์„ฑ๋˜์—ˆ๋‹ค.


๐Ÿ“Œ useCallback

  • useMemo์™€ ๋น„์Šทํ•˜๊ฒŒ ์ฃผ๋กœ ๋ Œ๋”๋ง ์„ฑ๋Šฅ์„ ์ตœ์ ํ™”ํ•ด์•ผ ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
  • useCallback ์€ ํŠน์ • ํ•จ์ˆ˜๋ฅผ ์ƒˆ๋กœ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ์žฌ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์„๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
  • ์ฒซ๋ฒˆ์งธ ์ธ์ž๋กœ ์ƒ์„ฑํ•˜๊ณ  ์‹ถ์€ ํ•จ์ˆ˜๋ฅผ ๋„ฃ๊ณ , ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ deps ๋ฐฐ์—ด์„ ๋„ฃ์–ด์ค€๋‹ค.
  • deps ๋ฐฐ์—ด ์•ˆ์— ์žˆ๋Š” ๋‚ด์šฉ์ด ๋ฐ”๋€Œ๋ฉด, ์ฒซ๋ฒˆ์งธ ์ธ์ž์˜ ํ•จ์ˆ˜๋ฅผ ์ƒˆ๋กœ ์ƒ์„ฑํ•˜๊ณ , ์•„๋‹ˆ๋ฉด ์ด์ „์— ๋ Œ๋”๋ง๋  ๋•Œ ์ƒ์„ฑํ•œ ํ•จ์ˆ˜๋ฅผ ์žฌ์‚ฌ์šฉํ•œ๋‹ค.
  • ๋งŒ์•ฝ deps์— ๋นˆ ๋ฐฐ์—ด์„ ๋„ฃ๊ฒŒ ๋˜๋ฉด, ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ฒ˜์Œ ๋ Œ๋”๋ง๋  ๋•Œ ๋งŒ๋“ค์—ˆ๋˜ ํ•จ์ˆ˜๋ฅผ ๊ณ„์† ์žฌ์‚ฌ์šฉํ•œ๋‹ค.
  • ๋ฐ˜๋ฉด, deps ์ธ์ž์— ์•„๋ฌด๊ฒƒ๋„ ๋„ฃ์ง€ ์•Š๋Š”๋‹ค๋ฉด ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋งค๋ฒˆ ๋ Œ๋”๋ง๋  ๋•Œ๋งˆ๋‹ค ์ฒซ๋ฒˆ์งธ ์ธ์ž์˜ ํ•จ์ˆ˜๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.
  • ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ ์ƒํƒœ ๊ฐ’์— ์˜์กดํ•ด์•ผ ํ•  ๋•Œ๋Š” ๊ทธ ๊ฐ’์„ ๋ฐ˜๋“œ์‹œ ๋‘ ๋ฒˆ์งธ ์ธ์ž์— ํฌํ•จํ•ด์•ผ ํ•œ๋‹ค.
import { useState, useMemo, useCallback } from "react";

const getAverage(numbers){
    console.log("ํ‰๊ท ๊ฐ’ ๊ณ„์‚ฐ์ค‘...");
    if (numbers.length === 0)  return 0;
    const sum = numbers.reduce((value, number) => value + number);
    return sum / numbers.length;
};


const Average = () => {
    const [list, setList] = useState([]);
    const [number, setNumber] = useState("");
    
    const onChange = useCallback((e) => {
        setNumber(e.target.value);
    }, []);
    
    const onInsert = useCallback(() => {
        setList(list.concat(parseInt(number));
        setNumber("");
    }, [list, number]);
    
    const avg = useMemo(() => getAverage(list), [list]);
    
    return (
        <div>
            <input
                type="text"
                name="number"
                value={number}
                onChange={onChange}/>
            <button onClick={onInsert}>๋“ฑ๋ก</button>
            <ul>
                {list.map((value, index) => (<li key={index}>{value}</li>))}
            </ul>
            <div>ํ‰๊ท ๊ฐ’: {avg}</div>
        </div>
    );

}

0๊ฐœ์˜ ๋Œ“๊ธ€