useCallback

Learn how to use the useCallback Hook in functional components.

We'll cover the following...

The useCallback Hook is used to optimize the performance of applications. It is used when we want to prevent unnecessary rerenders of a component. The useCallback receives a function and then creates a unique identity for that function, which remains active until the dependencies passed to the Hook have changed, i.e., the component will only rerender when the dependencies change. Dependencies can be the props passed to the component.

Usage

To implement and use the useCallback Hook, we first have to import it from the react library.

Press + to interact
import React, { useCallback } from "react";

Syntax

Once the useCallback Hook has been imported, we can use it inside our application.

Press + to interact
import React, { useState, useCallback } from 'react';
import {SafeAreaView, View, Text, Button, Alert, StyleSheet} from 'react-native';
const functions = new Set();
const App = () => {
const [age, setAge] = useState(25);
const [salary, setSalary] = useState(65000);
const incrementAge = useCallback(() => {
Alert.alert('incrementAge function rendered');
setAge(age + 1);
}, [age]);
const incrementSalary = useCallback(() => {
Alert.alert('incrementSalary function rendered');
setSalary(salary + 1000);
}, [salary]);
functions.add(incrementAge);
functions.add(incrementSalary);
return (
<SafeAreaView style={styles.container}>
<Text style={styles.text}> Age: { age } </Text>
<Text style={styles.text}> Salary: { salary } </Text>
<Text style={styles.text}> Newly created functions size: { functions.size }</Text>
<View style={styles.separator}></View>
<Button
title="Increment age"
onPress={ incrementAge }
/>
<View style={styles.separator}></View>
<Button
title="Increment salary"
onPress={ incrementSalary }
/>
<View style={styles.separator}></View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center"
},
text: {
fontSize: 30
},
separator: {
margin: 20
}
})
export default App;

The ...