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.
useCallback optimization in 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.
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);const sayHello = useCallback(() => {
console.log('Hello!');
}, []);const toggle = useCallback(() => {
setOn(prev => !prev);
}, []);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.
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> ); }
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.
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.