Skip to content

Latest commit

ย 

History

History
36 lines (27 loc) ยท 2.27 KB

UseCallback.md

File metadata and controls

36 lines (27 loc) ยท 2.27 KB

UseCallback

1.useCallback์ด๋ž€?

  • useCallback ๋˜ํ•œ useMemo์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋ฉ”๋ชจ์ด์ œ์ด์…˜ ๊ธฐ๋ฒ•์„ ์ด์šฉํ•œ Hook

  • useMemo๋Š” ๊ฐ’์˜ ์žฌ์‚ฌ์šฉ์„ ์œ„ํ•ด ์‚ฌ์šฉํ•˜๋Š” Hook์ด๋ผ๋ฉด, useCallback์€ ํ•จ์ˆ˜์˜ ์žฌ์‚ฌ์šฉ์„ ์œ„ํ•ด ์‚ฌ์šฉํ•˜๋Š” Hook์ž„

    import React, { useCallback } from "react"; // import ํ•„์š”
    
    function Caculator({x, y}){
        const add = useCallback(() => x + y, [x, y]);
    
        return <>
            <div>
                {add()}
            </div>
        </>;
    }
  • useCallback Hook์„ ์‚ฌ์šฉํ•˜๋ฉด ๊ทธ ํ•จ์ˆ˜๊ฐ€ ์˜์กดํ•˜๋Š” ๊ฐ’๋“ค์ด ๋ฐ”๋€Œ์ง€ ์•Š๋Š” ํ•œ ๊ธฐ์กด ํ•จ์ˆ˜๋ฅผ ๊ณ„์†ํ•ด์„œ ๋ฐ˜ํ™˜ํ•จ. ์ฆ‰ ์œ„์˜ ์˜ˆ์‹œ์—์„œ x์™€ y๊ฐ’์ด ๋™์ผํ•˜๋‹ค๋ฉด ๋‹ค์Œ ๋ Œ๋”๋ง ๋•Œ ์ด ํ•จ์ˆ˜๋ฅผ ๋‹ค์‹œ ์‚ฌ์šฉํ•จ.

  • ๋‹จ, useCallback๋งŒ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด useMemo์— ๋น„ํ•ด ๊ด„๋ชฉํ•  ๋งŒํ•œ ์ตœ์ ํ™”๋ฅผ ๋Š๋‚„ ์ˆ˜๋Š” ์—†์Œ

  • useCallback์€ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ์„ ํ•˜์ง€ ์•Š๋Š” Hook์ด ์•„๋‹ˆ๋ผ, ๊ทธ์ € ๋ฉ”๋ชจ๋ฆฌ ์–ด๋”˜๊ฐ€์— ํ•จ์ˆ˜๋ฅผ ๊บผ๋‚ด์„œ ํ˜ธ์ถœํ•˜๋Š” Hook์ด๊ธฐ ๋•Œ๋ฌธ

  • ๋”ฐ๋ผ์„œ ๋‹จ์ˆœํžˆ ์ปดํฌ๋„ŒํŠธ ๋‚ด์—์„œ ํ•จ์ˆ˜๋ฅผ ๋ฐ˜๋ณตํ•ด์„œ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ธฐ ์œ„ํ•ด useCallback์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค, ์ž์‹ ์ปดํฌ๋„ŒํŠธ์˜ props๋กœ ํ•จ์ˆ˜๋ฅผ ์ „๋‹ฌํ•ด ์ค„ ๋•Œ ์‚ฌ์šฉํ•˜๊ธฐ ์ข‹์Œ.


2. useCallback๊ณผ ์ฐธ์กฐ ๋™๋“ฑ์„ฑ

  • useCallback์€ ์ฐธ์กฐ ๋™๋“ฑ์„ฑ์— ์˜์กดํ•จ.
  • React๋Š” JavaScript ์–ธ์–ด๋กœ ๋งŒ๋“ค์–ด์ง„ ์˜คํ”ˆ์†Œ์Šค ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ด๊ธฐ์— ๊ธฐ๋ณธ์ ์œผ๋กœ JavaScript์˜ ๋ฌธ๋ฒ•์„ ๋”ฐ๋ผ๊ฐ.
  • JavaScript์—์„œ ํ•จ์ˆ˜๋Š” ๊ฐ์ฒด์ธ๋ฐ, ๊ฐ์ฒด๋Š” ๋ฉ”๋ชจ๋ฆฌ์— ์ €์žฅํ•  ๋•Œ ๊ฐ’์„ ์ €์žฅํ•˜๋Š” ๊ฒŒ ์•„๋‹ˆ๋ผ ๊ฐ’์˜ ์ฃผ์†Œ๋ฅผ ์ €์žฅํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฐ’์ด ๊ฐ™์„์ง€๋ผ๋„ ์ผ์น˜์—ฐ์‚ฐ์ž๋กœ ๋น„๊ตํ–ˆ์„ ๋•Œ false๊ฐ€ ์ถœ๋ ฅ๋จ.
  • React๋„ ๋งˆ์ฐฌ๊ฐ€์ง€. React๋Š” ๋ฆฌ๋ Œ๋”๋ง ์‹œ ํ•จ์ˆ˜๋ฅผ ์ƒˆ๋กœ์ด ๋งŒ๋“ค์–ด์„œ ํ˜ธ์ถœ์„ ํ•˜๋ฉฐ, ์ƒˆ๋กœ์ด ๋งŒ๋“ค์–ด ํ˜ธ์ถœ๋œ ํ•จ์ˆ˜๋Š” ๊ธฐ์กด์˜ ํ•จ์ˆ˜์™€ ๊ฐ™์€ ํ•จ์ˆ˜๊ฐ€ ์•„๋‹˜
  • ๊ทธ๋Ÿฌ๋‚˜ useCallback์„ ์ด์šฉํ•ด ํ•จ์ˆ˜ ์ž์ฒด๋ฅผ ์ €์žฅํ•ด์„œ ๋‹ค์‹œ ์‚ฌ์šฉํ•˜๋ฉด ํ•จ์ˆ˜์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ ๊ฐ’์„ ์ €์žฅํ–ˆ๋‹ค๊ฐ€ ๋‹ค์‹œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ.
  • ๋”ฐ๋ผ์„œ React ์ปดํฌ๋„ŒํŠธ ํ•จ์ˆ˜ ๋‚ด์—์„œ ๋‹ค๋ฅธ ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ๋„˜๊ธฐ๊ฑฐ๋‚˜ ์ž์‹ ์ปดํฌ๋„ŒํŠธ์˜ prop์œผ๋กœ ๋„˜๊ธธ ๋•Œ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์„ฑ๋Šฅ ๋ฌธ์ œ๋ฅผ ๋ง‰์„ ์ˆ˜ ์žˆ์Œ.