useMemo

Learn how to use the useMemo Hook in functional components.

We'll cover the following...

The useMemo Hook is used to store or cache the results of expensive calculations and computations between rerenders of a component. This improves the performance of the application since the expensive computations do not have to be calculated every time the component rerenders.

Usage

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

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

Syntax

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

Press + to interact
import React, { useState, useMemo, useEffect } from 'react';
import { SafeAreaView, Text, View, Button, Alert, StyleSheet } from 'react-native';
const App = () => {
const [counter, setCounter] = useState(0);
const [value, setValue] = useState(12);
const fib = (n) => (n < 2) ? n : fib(n-1) + fib(n - 2);
const storedResult = useMemo(() => fib(value), [value]);
useEffect(() => {
Alert.alert("Component rendered");
}, [counter]);
return (
<SafeAreaView style={styles.container}>
<Text style={styles.text}> Fibonacci value: { storedResult } </Text>
<View style={styles.separator}></View>
<Text style={styles.text}> Counter value: { counter } </Text>
<View style={styles.separator}></View>
<Button
title="Increment Counter"
onPress={() => setCounter(counter + 1)}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
text: {
fontSize: 35
},
separator: {
margin: 15
},
});
export default App;

The useMemo Hook takes these two arguments:

  • Function: This is a function that does expensive computations. In ...