Bird
Raised Fist0
React Nativemobile~20 mins

useCallback optimization in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Counter with useCallback
A simple counter app that uses useCallback to optimize button press handlers and avoid unnecessary re-renders.
Target UI
Counter with useCallback Optimization

+-------------------------+
| Count: 0                |
|                         |
| [Increment] [Decrement] |
+-------------------------+
Display a count number starting at 0
Two buttons: Increment and Decrement
Use useCallback to memoize the increment and decrement functions
Buttons should update the count correctly
Avoid unnecessary re-renders of buttons by using React.memo
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const CounterScreen = () => {
  const [count, setCount] = useState(0);

  // TODO: Use useCallback to memoize increment and decrement functions

  return (
    <View style={styles.container}>
      <Text style={styles.countText}>Count: {count}</Text>
      <View style={styles.buttonRow}>
        <Button title="Increment" onPress={() => setCount(count + 1)} />
        <Button title="Decrement" onPress={() => setCount(count - 1)} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  countText: { fontSize: 32, marginBottom: 20 },
  buttonRow: { flexDirection: 'row', width: '60%', justifyContent: 'space-around' },
});

export default CounterScreen;
Task 1
Task 2
Task 3
Task 4
Solution
React Native
import React, { useState, useCallback, memo } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const MemoButton = memo(({ title, onPress }) => {
  return <Button title={title} onPress={onPress} />;
});

const CounterScreen = () => {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount(c => c + 1);
  }, []);

  const decrement = useCallback(() => {
    setCount(c => c - 1);
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.countText}>Count: {count}</Text>
      <View style={styles.buttonRow}>
        <MemoButton title="Increment" onPress={increment} />
        <MemoButton title="Decrement" onPress={decrement} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  countText: { fontSize: 32, marginBottom: 20 },
  buttonRow: { flexDirection: 'row', width: '60%', justifyContent: 'space-around' },
});

export default CounterScreen;

We use useCallback to create increment and decrement functions that do not change on every render. This helps React avoid re-rendering child components that depend on these functions.

We also wrap the Button component inside a MemoButton using React.memo. This means the buttons only re-render if their props change.

Using setCount(c => c + 1) inside the callbacks ensures we always update the latest count value without needing to add count as a dependency.

This optimization is useful in bigger apps to improve performance by reducing unnecessary renders.

Final Result
Completed Screen
Counter with useCallback Optimization

+-------------------------+
| Count: 0                |
|                         |
| [Increment] [Decrement] |
+-------------------------+
Tapping Increment increases the count by 1
Tapping Decrement decreases the count by 1
Buttons do not re-render unnecessarily when count changes
Stretch Goal
Add a Reset button that resets the count to zero using useCallback
💡 Hint
Create a memoized reset function with useCallback and add a new MemoButton for Reset

Practice

(1/5)
1. What is the main purpose of useCallback in React Native?
easy
A. To create new state variables
B. To prevent functions from being recreated on every render
C. To style components dynamically
D. To fetch data from an API

Solution

  1. Step 1: Understand function recreation in React

    Functions inside components are recreated on every render by default, which can cause unnecessary work.
  2. Step 2: Role of useCallback

    useCallback memoizes the function, so it keeps the same reference unless dependencies change.
  3. Final Answer:

    To prevent functions from being recreated on every render -> Option B
  4. Quick Check:

    useCallback = prevent function recreation [OK]
Hint: useCallback keeps functions stable between renders [OK]
Common Mistakes:
  • Thinking useCallback creates state
  • Confusing useCallback with styling
  • Assuming useCallback fetches data
2. Which of the following is the correct syntax to use useCallback?
easy
A. const memoizedFn = useCallback(doSomething, dependency);
B. const memoizedFn = useCallback(() => { doSomething(); });
C. const memoizedFn = useCallback(() => { doSomething(); }, [dependency]);
D. const memoizedFn = useCallback(doSomething, [dependency]);

Solution

  1. Step 1: Check useCallback parameters

    useCallback takes a function and an array of dependencies as parameters.
  2. Step 2: Validate correct syntax

    const memoizedFn = useCallback(() => { doSomething(); }, [dependency]); correctly passes an arrow function and an array of dependencies.
  3. Final Answer:

    const memoizedFn = useCallback(() => { doSomething(); }, [dependency]); -> Option C
  4. Quick Check:

    useCallback syntax = function + [dependencies] [OK]
Hint: useCallback needs a function and dependency array [OK]
Common Mistakes:
  • Omitting dependency array
  • Passing dependencies without array brackets
  • Passing function reference without wrapping in arrow function
3. What will be the output of the following code snippet?
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount(count + 1), []);

increment();
increment();
console.log(count);
medium
A. 2
B. Error
C. 1
D. 0

Solution

  1. Step 1: Analyze useCallback dependencies

    The callback uses count but has an empty dependency array, so it captures the initial value 0.
  2. Step 2: Effect of calling increment()

    Calling increment() calls setCount(0 + 1) twice, but React batches updates and count remains 0 in this synchronous context.
  3. Final Answer:

    0 -> Option D
  4. Quick Check:

    Empty dependencies cause stale count = 0 [OK]
Hint: Empty deps cause stale closure values [OK]
Common Mistakes:
  • Assuming count updates immediately
  • Ignoring stale closure from empty deps
  • Expecting increment to add twice
4. Identify the issue in this code and how to fix it:
const [value, setValue] = useState(0);
const updateValue = useCallback(() => {
  setValue(value + 1);
}, []);
medium
A. Missing dependency 'value' in useCallback array; add [value]
B. setValue should be outside useCallback
C. useCallback should not be used here
D. No issue; code is correct

Solution

  1. Step 1: Check dependencies in useCallback

    The callback uses value but the dependency array is empty, causing stale closure.
  2. Step 2: Fix by adding dependency

    Add value to the dependency array to update the callback when value changes.
  3. Final Answer:

    Missing dependency 'value' in useCallback array; add [value] -> Option A
  4. Quick Check:

    Dependencies must include all used variables [OK]
Hint: Always include variables used inside useCallback deps [OK]
Common Mistakes:
  • Leaving dependency array empty
  • Removing useCallback instead of fixing deps
  • Misplacing setValue call
5. You have a parent component passing a callback to a child. The callback depends on multiple state variables. How should you optimize it with useCallback to avoid unnecessary re-renders of the child?
hard
A. Wrap the callback with useCallback including all dependent state variables in the dependency array
B. Wrap the callback with useCallback but leave dependency array empty
C. Do not use useCallback; define the callback inline in the child
D. Use useMemo instead of useCallback for the callback

Solution

  1. Step 1: Understand callback dependencies

    The callback depends on multiple state variables, so it must update when any of them change.
  2. Step 2: Use useCallback with all dependencies

    Include all dependent state variables in the dependency array to keep the callback updated and stable.
  3. Step 3: Avoid empty dependency array

    Leaving it empty causes stale values and bugs; defining inline causes new function each render.
  4. Final Answer:

    Wrap the callback with useCallback including all dependent state variables in the dependency array -> Option A
  5. Quick Check:

    All dependencies in useCallback deps = stable, updated callback [OK]
Hint: Include all used states in useCallback deps to optimize [OK]
Common Mistakes:
  • Leaving deps empty causing stale closures
  • Defining callback inline causing re-renders
  • Confusing useMemo with useCallback
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard