The useEffect hook lets your React Native app do things after rendering, like fetching data or updating the screen. It helps your app react to changes smoothly.
0
0
useEffect hook in React Native
Introduction
When you want to load data from the internet after the screen shows up.
When you need to update the screen after a user changes something.
When you want to set up a timer or interval that runs repeatedly.
When you want to clean up resources like stopping a timer when leaving a screen.
Syntax
React Native
useEffect(() => {
// code to run after render or when dependencies change
return () => {
// optional cleanup code
};
}, [dependencies]);The first argument is a function that runs after the component renders.
The second argument is an array of dependencies; the effect runs when these change. If empty, it runs only once after the first render.
Examples
This runs only once when the component first appears.
React Native
useEffect(() => {
console.log('Runs once after first render');
}, []);This runs every time the
count value changes.React Native
useEffect(() => {
console.log('Runs when count changes:', count);
}, [count]);This sets up a timer when the component mounts and cleans it up when it unmounts.
React Native
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(timer);
}, []);Sample App
This component shows a number and a button. When you press the button, the number increases. The useEffect logs the new number every time it changes.
React Native
import React, { useState, useEffect } from 'react'; import { View, Text, Button } from 'react-native'; export default function Counter() { const [count, setCount] = useState(0); useEffect(() => { console.log(`Count changed to ${count}`); }, [count]); return ( <View style={{ padding: 20 }}> <Text style={{ fontSize: 24 }}>Count: {count}</Text> <Button title="Increase" onPress={() => setCount(count + 1)} /> </View> ); }
OutputSuccess
Important Notes
Always include the dependency array to control when the effect runs.
Cleanup functions help avoid memory leaks, especially with timers or subscriptions.
Effects run after the screen updates, so they don't block the UI.
Summary
useEffect runs code after your component renders or updates.
Use it to fetch data, update things, or clean up resources.
Control when it runs by listing dependencies in an array.