The useCallback hook is used to memoize a callback function, preventing unnecessary re-renders and improving performance.
Solution Code
React Native
-- Example Code --
import React, { useState, useCallback } from "react";
import { View, Text, Button } from "react-native";
const App = () => {
const [count, setCount] = useState(0);
const [text, setText] = useState("Hello");
const handleChange = useCallback((newText) => {
setText(newText);
}, []);
return (
<View>
<Text>{text}</Text>
<Button title="Increment" onPress={() => setCount(count + 1)} />
<Button title="Change Text" onPress={() => handleChange("New Text")} />
</View>
);
};
export default App;
Explanation
This code demonstrates how to use the useCallback hook to memoize a callback function.Guided Hints
{'hint': 'Use useCallback to memoize callback functions.'}
{'hint': 'It prevents unnecessary re-renders.'}