CodeBlanks Logo Icon CodeBlanks

Summary - Performance

Combine React.memo, useCallback and useMemo to write an optimized list.

Summary - Performance

In this group you learned five tools for performance. React.memo skips a component unless props change. useCallback keeps a function reference stable. useMemo caches the result of an expensive computation. FlatList optimization with getItemLayout and keyExtractor speeds up scrolling.

InteractionManager defers heavy work until after interactions. Using these five together keeps a real app smooth. Adding all of them everywhere is not right; add them with measure and need. Use the Profiler to see where the bottleneck is, then pick the matching tool.

Practice Memoized card and useCallback

A Card component is already defined; it takes a title prop. Create MemoCard with React.memo. Inside the App component hold a count state; define handlePress with useCallback (deps []). Pass title={count.toString()} to MemoCard.

Starter code

App.js
import React, { useState, useCallback } from 'react';
import { Text, View } from 'react-native';

function Card({ title }) {
  return <Text>{title}</Text>;
}

// Create MemoCard with React.memo

export default function App() {
  const [count, setCount] = useState(0);
  // Define handlePress with useCallback; deps is empty array

  // Pass title={count.toString()} to MemoCard
  return null;
}

Sample solution

App.js
import React, { useState, useCallback } from "react";
import { Text, View } from "react-native";

function Card({ title }) {
  return <Text>{title}</Text>;
}

const MemoCard = React.memo(Card);

export default function App() {
  const [count, setCount] = useState(0);
  const handlePress = useCallback(() => {
    setCount((c) => c + 1);
  }, []);
  return <MemoCard title={count.toString()} />;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 To keep a function reference stable?

App.js
const fn = ???(() => {}, []);
  • useCallback Correct answer
  • React.memo
  • useMemo
  • InteractionManager

Explanation: useCallback keeps a function reference stable.

2 Match each tool to its purpose

Term Meaning
React.memo Wraps a component
useCallback Stores a function
useMemo Caches a value
InteractionManager Defers work

3 useCallback import

Question
import { ____, useState } from 'react';
Answer
import { useCallback, useState } from 'react';

Explanation: useCallback is imported from React.

All lessons in Intermediate