import React, { useState, useCallback, memo } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
const MemoButton = memo(({ title, onPress }) => {
return <Button title={title} onPress={onPress} />;
});
const CounterScreen = () => {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []);
const decrement = useCallback(() => {
setCount(c => c - 1);
}, []);
return (
<View style={styles.container}>
<Text style={styles.countText}>Count: {count}</Text>
<View style={styles.buttonRow}>
<MemoButton title="Increment" onPress={increment} />
<MemoButton title="Decrement" onPress={decrement} />
</View>
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
countText: { fontSize: 32, marginBottom: 20 },
buttonRow: { flexDirection: 'row', width: '60%', justifyContent: 'space-around' },
});
export default CounterScreen;We use useCallback to create increment and decrement functions that do not change on every render. This helps React avoid re-rendering child components that depend on these functions.
We also wrap the Button component inside a MemoButton using React.memo. This means the buttons only re-render if their props change.
Using setCount(c => c + 1) inside the callbacks ensures we always update the latest count value without needing to add count as a dependency.
This optimization is useful in bigger apps to improve performance by reducing unnecessary renders.