0Pricing
React Native Academy · 강의

성능을 위한 useCallback과 useMemo

useCallback으로 콜백 함수를 메모이제이션하여 불필요한 자식 컴포넌트 재렌더링을 방지하고, 비용이 큰 계산 값을 useMemo로 캐시합니다.

성능을 위한 useCallback과 useMemo은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

The Re-Render Problem

Every time a component re-renders in React, all values created inside the function body are recreated. This includes objects, arrays, and most importantly — functions. If a recreated function or value is passed as a prop to a child component, the child sees a new reference and re-renders, even when the logical value has not changed.

What is useCallback?

useCallback(fn, deps) returns a memoized version of the callback function that only changes if one of the dependencies has changed. Wrapping a callback in useCallback preserves the same function reference across renders, preventing unnecessary re-renders in child components that receive it as a prop.

import { useCallback } from 'react';

function Parent() {
  const [count, setCount] = useState(0);

  // handlePress is the SAME function reference between renders
  // as long as count does not change
  const handlePress = useCallback(() => {
    console.log('Pressed, count is:', count);
  }, [count]);

  return <Child onPress={handlePress} />;
}

useCallback with React.memo

useCallback is most effective when paired with React.memo on the child component. Without React.memo the child re-renders anyway regardless of prop reference equality. The combination of React.memo on the child and useCallback on the parent callback prevents re-renders when neither the behavior nor the data has changed.

const ChildButton = React.memo(({ onPress, label }) => (
  <Button title={label} onPress={onPress} />
));

function Parent() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

  // ChildButton will NOT re-render when text changes
  const handleCount = useCallback(() => setCount(c => c + 1), []);

  return (
    <>
      <TextInput value={text} onChangeText={setText} />
      <ChildButton label='Count' onPress={handleCount} />
    </>
  );
}

What is useMemo?

useMemo(computeFn, deps) memoizes the result of an expensive computation. React calls computeFn on the first render and caches its return value. On subsequent renders it returns the cached value unless a dependency has changed. This avoids repeating heavy calculations every render.

import { useMemo } from 'react';

function ProductList({ products, category }) {
  // Only recomputes when products or category changes
  const filtered = useMemo(
    () => products.filter((p) => p.category === category),
    [products, category]
  );

  return <FlatList data={filtered} renderItem={renderItem} />;
}

useMemo for Stable Object References

Objects and arrays created inline in JSX are new references on every render. If passed to a memoized child, they defeat memoization. Wrap them in useMemo to create a stable reference that only changes when the underlying data changes. This is especially important for style arrays and config objects.

function Chart({ data, color }) {
  // New object on every render without useMemo
  const chartConfig = useMemo(() => ({
    backgroundColor: color,
    dataPoints: data.map((d) => d.value),
  }), [data, color]);

  return <ChartComponent config={chartConfig} />;
}

Dependency Arrays: Getting Them Right

Both useCallback and useMemo require accurate dependency arrays. Include every value from the component scope that is used inside the memoized function or computation. Missing a dependency causes the memoized value to use a stale closure; listing too many causes unnecessary recomputation. ESLint's exhaustive-deps rule helps enforce correctness.

// Wrong: missing userId dependency — stale closure bug
const fetchUser = useCallback(() => fetch('/user/' + userId), []);

// Correct: userId is listed
const fetchUser = useCallback(() => fetch('/user/' + userId), [userId]);

When NOT to Use useCallback

useCallback has a cost: React stores the function in memory and checks the dependency array on every render. For simple handlers that are not passed to memoized children, the overhead of useCallback exceeds the benefit. Use it selectively — only when the child component is wrapped in React.memo and props equality matters for performance.

// Unnecessary: Button re-renders anyway; no child is memoized
const handlePress = useCallback(() => setVisible(true), []);

// Fine without useCallback in this case
const handlePress = () => setVisible(true);

useMemo for Expensive Transformations

Use useMemo when a computation takes noticeable time — sorting large arrays, parsing complex data, running statistical calculations. The rule of thumb: if the computation takes more than a millisecond and runs on every render, consider memoizing it. For trivial operations (adding two numbers), the memoization overhead is larger than the computation itself.

const sortedAndFiltered = useMemo(() => {
  return items
    .filter((item) => item.status === selectedStatus)
    .sort((a, b) => b.createdAt - a.createdAt)
    .slice(0, 100);
}, [items, selectedStatus]);

useCallback for renderItem in FlatList

Wrapping the renderItem function of a FlatList in useCallback prevents a new function reference from being created on every parent render, which would cause every visible FlatList row to re-render. This is one of the most impactful performance wins in list-heavy React Native apps.

const renderItem = useCallback(({ item }) => (
  <ProductCard
    product={item}
    onPress={handleSelectProduct}
  />
), [handleSelectProduct]); // handleSelectProduct also memoized

<FlatList
  data={products}
  renderItem={renderItem}
  keyExtractor={(item) => item.id}
/>

Measuring the Impact

Before adding memoization everywhere, measure the actual impact using the React DevTools Profiler. Record an interaction, look at the flame chart to identify components that re-render unnecessarily, and only add useCallback or useMemo where the profiler shows a real bottleneck. Premature optimization adds code complexity with no measurable benefit.

Summary Comparison

Remember the key difference: useCallback memoizes a function (prevents recreating the function reference), while useMemo memoizes a computed value (prevents re-running an expensive calculation). Both accept a dependency array and only recompute when the listed dependencies change.

// useCallback — memoize a function
const fn = useCallback(() => doSomething(a, b), [a, b]);

// useMemo — memoize a computed value
const val = useMemo(() => computeExpensive(a, b), [a, b]);

// Relationship: useCallback(fn, deps) === useMemo(() => fn, deps)

Quick Check

Test your understanding of useCallback and useMemo for performance from this lesson.

Lesson Recap

In this lesson you learned: useCallback memoizes a function reference to prevent unnecessary child re-renders, useMemo memoizes an expensive computed value to skip re-calculation on every render, and both work best when combined with React.memo and accurate dependency arrays. Next up we explore writing custom hooks to share stateful logic between components.

자주 묻는 질문

“성능을 위한 useCallback과 useMemo” 강의는 무료인가요?

네 — “성능을 위한 useCallback과 useMemo” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“성능을 위한 useCallback과 useMemo”에서 뭘 배우나요?

useCallback으로 콜백 함수를 메모이제이션하여 불필요한 자식 컴포넌트 재렌더링을 방지하고, 비용이 큰 계산 값을 useMemo로 캐시합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“성능을 위한 useCallback과 useMemo” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. DOM 노드와 변경 가능한 값에 useRef 사용하기
  2. 복잡한 상태 로직에 useReducer 사용하기
  3. 성능을 위한 useCallback과 useMemo
  4. 사용자 지정 훅 작성하기
← React Native Academy(으)로 돌아가기