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.
useEffect hook in 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.
useEffect(() => {
console.log('Runs once after first render');
}, []);count value changes.useEffect(() => {
console.log('Runs when count changes:', count);
}, [count]);useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(timer);
}, []);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.
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> ); }
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.
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.
Practice
useEffect hook do in a React Native component?Solution
Step 1: Understand the purpose of useEffect
TheuseEffecthook is designed to run side effects after rendering or updating a component.Step 2: Compare with other React Native features
Declaring state is done withuseState, UI layout is JSX, and event handling uses props or handlers, notuseEffect.Final Answer:
Runs code after the component renders or updates -> Option CQuick Check:
useEffect runs after render/update = A [OK]
- Confusing useEffect with useState
- Thinking useEffect defines UI
- Assuming useEffect handles events directly
useEffect only once when the component mounts?Solution
Step 1: Identify how to run useEffect once
Passing an empty dependency array[]makesuseEffectrun only once after the first render.Step 2: Analyze other options
Omitting the dependency array runs on every render, and passing non-array values liketrueornullcauses a type error since the second argument must be an array.Final Answer:
useEffect(() => { /* code */ }, []); -> Option BQuick Check:
Empty array means run once = A [OK]
- Forgetting the empty array causes repeated runs
- Using non-empty arrays thinking it runs once
- Omitting the dependency array
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count is', count);
}, [count]);
setCount(1);
setCount(2);What will be printed in the console?
Solution
Step 1: Understand useEffect dependency on count
The effect runs after render whencountchanges. It logs the currentcountvalue.Step 2: Analyze setCount calls
CallingsetCount(1)then immediatelysetCount(2)causes React to batch updates, so only the last value (2) triggers a render and effect.Final Answer:
Count is 2 -> Option DQuick Check:
Last setCount triggers effect with 2 = C [OK]
- Thinking both setCount calls trigger separate effects
- Expecting initial count log
- Ignoring React's batching of state updates
useEffect(() => {
fetchData();
}, fetchData);Assuming
fetchData is a function defined outside the component.Solution
Step 1: Check dependency argument type
The second argument touseEffectmust be an array listing dependencies, not a function.Step 2: Understand correct usage
To run effect whenfetchDatachanges, pass[fetchData]. Passing justfetchDatacauses a type error.Final Answer:
Dependency array should be an array, not a function -> Option AQuick Check:
Dependency must be array = B [OK]
- Passing a function instead of an array
- Omitting dependency array thinking it's optional
- Confusing function call with dependency list
Solution
Step 1: Identify when to run fetchUserData
The fetch should run only whenuserIdchanges, souserIdmust be in the dependency array.Step 2: Evaluate options
useEffect(() => { fetchUserData(); }, []); runs only once, ignoring userId changes. useEffect(() => { fetchUserData(); }); runs every render. useEffect(() => { fetchUserData(userId); }, [fetchUserData]); depends onfetchUserData, which is likely stable or external, not userId.Final Answer:
useEffect(() => { fetchUserData(); }, [userId]); -> Option AQuick Check:
Dependency array with userId triggers fetch on change = D [OK]
- Leaving dependency array empty when value changes
- Omitting dependency array causing too many fetches
- Using wrong dependencies causing missed updates
Ready to prove it?
Pass the test and this pattern moves unknown
