ํ”„๋กœ๊ทธ๋ž˜๋ฐ/React JS

[React] ์„ฑ๋Šฅ ์ตœ์ ํ™” useCallback์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๊ธฐ

์šฉ๋‡ฝ 2023. 7. 24. 18:08
๋ฐ˜์‘ํ˜•

[React] ์„ฑ๋Šฅ ์ตœ์ ํ™” useCallback์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๊ธฐ

๐Ÿ“– ๋“ค์–ด๊ฐ€๋ฉฐ

์ด์ „ ๊ธ€ React.memo ๊ธ€์—์„œ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์—์„œ ํ•จ์ˆ˜๋ฅผ props๋กœ ๋ฐ›์„ ๋•Œ ํ•ด๊ฒฐํ•  ์ˆ˜ ์—†๋Š” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” useCallback์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

useCallback์ด๋ž€ โ“

๋จผ์ € React์—์„œ useCallback์€ ๋ฆฌ๋ Œ๋”๋ง ์‚ฌ์ด์— ํ•จ์ˆ˜ ์ •์˜๋ฅผ ์บ์‹œ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” React ํ›…์ž…๋‹ˆ๋‹ค.

์ฆ‰, useCallback ํ›…์€ ๊ธฐ๋ณธ์ ์œผ๋กœ ์ปดํฌ๋„ŒํŠธ ์‹คํ–‰ ์ „๋ฐ˜์— ๊ฑธ์ณ ํ•จ์ˆ˜๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š” ํ›…์œผ๋กœ React์— ํ•จ์ˆ˜๋ฅผ ์บ์‹ฑํ•˜๊ณ  ๋งค ์‹คํ–‰๋งˆ๋‹ค ํ•ด๋‹น ํ•จ์ˆ˜๋ฅผ ์žฌ์ƒ์„ฑ๋˜๋Š” ์ƒํ™ฉ์„ ๋ง‰์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์‚ฌ์šฉ ๋ฐฉ๋ฒ•

์บ์‹ฑํ•˜๋ ค๋Š” ํ•จ์ˆ˜๋ฅผ useCallback์œผ๋กœ ๋ž˜ํ•‘ ํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

// Button.js

const Button = ({ onClick }) => {
  console.log('Button RUNNING');

  return <button onClick={onClick}>ํด๋ฆญ</button>;
};

export default React.memo(Button);

// App.js
import React, { useState, useCallback } from 'react';

function App() {
  const [toggleState, setToggleState] = useState(false);
  console.log('APP RUNNING');

  const toggleStateHandler = useCallback(() => {
    setToggleState((prev) => !prev);
  }, []);

  return (
    <div className="app">
      <Button onClick={toggleStateHandler}>Toggle State</Button>
    </div>
  );
}

export default App;

ํ•จ์ˆ˜๋ฅผ ์ฒซ ๋ฒˆ์งธ ์ธ์ž๋กœ ์ „๋‹ฌํ•˜๋ฉด useCallback์€ ์บ์‹ฑ๋œ ํ•จ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ , ์ด App ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋‹ค์‹œ ์‹คํ–‰๋˜๋ฉด useCallback์ด React์— ์บ์‹œ ๋œ ํ•จ์ˆ˜๋ฅผ ์ฐพ์•„์„œ ๊ฐ™์€ ํ•จ์ˆ˜ ๊ฐ์ฒด๋ฅผ ์žฌ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด useCallback๊ณผ React.memo ๋•๋ถ„์— ๋ฌด๋ถ„๋ณ„ํ•œ ๋ฆฌ๋ Œ๋”๋ง์„ ๋ง‰์„ ์ˆ˜ ์žˆ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

๋ฐ˜์‘ํ˜•

์˜์กด์„ฑ ๋ฐฐ์—ด

useEffect์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ, useCallback์€ ๋‘ ๋ฒˆ์งธ ์ธ์ž๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.

๋ฐ”๋กœ useCallback ํ˜ธ์ถœ์— ๋Œ€ํ•œ ์˜์กด์„ฑ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.

์ด ์˜์กด์„ฑ ๋ฐฐ์—ด์€ useEffect์™€ ๊ฐ™์€ ๊ฒƒ์„ ์˜๋ฏธํ•˜๊ณ  ํ•จ์ˆ˜๋ฅผ ๊ฐ์‹ผ ์ปดํฌ๋„ŒํŠธ๋กœ๋ถ€ํ„ฐ ์ „๋‹ฌ๋ฐ›๋Š” ๋ชจ๋“  ๊ฒƒ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋งˆ์ฐฌ๊ฐ€์ง€๋กœ, ๋นˆ ๋ฐฐ์—ด์„ ๋„ฃ๊ฒŒ ๋˜๋ฉด ์ฒซ ํ˜ธ์ถœ ์ดํ›„ ์žฌ ํ˜ธ์ถœ ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์‚ฌ์šฉํ•˜๋ฉด ์ข‹์€ ์ƒํ™ฉ

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

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

 

๋ฐ˜์‘ํ˜•