0
0
React Nativemobile~5 mins

useCallback optimization in React Native

Choose your learning style9 modes available
Introduction

useCallback helps your app remember a function so it doesn't get recreated every time the screen updates. This makes your app faster and smoother.

When you pass a function to a child component and want to avoid unnecessary updates.
When you have a function inside your component that depends on some values and you want to keep it stable unless those values change.
When you want to improve performance by preventing functions from being recreated on every render.
When you use functions in hooks like useEffect and want to avoid running effects too often.
Syntax
React Native
const memoizedFunction = useCallback(() => {
  // function code here
}, [dependencies]);

The function inside useCallback is only recreated if one of the dependencies changes.

Dependencies are values your function uses from outside its own scope.

Examples
This function increases count and only changes when count changes.
React Native
const increment = useCallback(() => {
  setCount(count + 1);
}, [count]);
This function never changes because it has no dependencies.
React Native
const sayHello = useCallback(() => {
  console.log('Hello!');
}, []);
This function toggles a boolean state and uses the previous value, so it has no dependencies.
React Native
const toggle = useCallback(() => {
  setOn(prev => !prev);
}, []);
Sample App

This app shows a number and a button. When you press the button, the number goes up by one. The increment function is remembered and not recreated every time the screen updates, making the app smoother.

React Native
import React, { useState, useCallback } from 'react';
import { View, Button, Text } from 'react-native';

export default function Counter() {
  const [count, setCount] = useState(0);

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

  return (
    <View style={{ padding: 20 }}>
      <Text style={{ fontSize: 24, marginBottom: 10 }}>Count: {count}</Text>
      <Button title="Increment" onPress={increment} />
    </View>
  );
}
OutputSuccess
Important Notes

Remember to list all variables your function uses inside the dependency array.

If you leave dependencies empty, your function won't update when those variables change, which can cause bugs.

useCallback is mainly for optimization; don't use it everywhere unnecessarily.

Summary

useCallback keeps functions from being recreated on every screen update.

Use it when passing functions to child components or in hooks to improve performance.

Always include dependencies your function uses to keep it updated correctly.