useEffect Hook
The useEffect hook allows React Native components to perform side effects such as fetching data, subscribing to events, or setting up timers. This tutorial explains how useEffect works and how to use it correctly.
Basic Syntax
useEffect accepts a function containing the side effect logic and an optional dependency array that controls when the effect runs.
Running Effects Only Once
Passing an empty dependency array causes the effect to run only once, immediately after the component mounts, similar to componentDidMount in class components.
Running Effects on Specific Dependency Changes
Adding variables to the dependency array causes the effect to re-run whenever any of those values change between renders.
Cleanup Functions
useEffect can return a cleanup function, which runs before the component unmounts or before the effect runs again, useful for clearing timers or unsubscribing from listeners.
Fetching Data with useEffect
A common pattern is fetching API data when a component first mounts, storing the result using useState.
Common Mistakes
- Forgetting the dependency array, causing the effect to run on every render
- Missing dependencies that are used inside the effect
- Not cleaning up subscriptions or timers, leading to memory leaks
Conclusion
The useEffect hook is essential for managing side effects in React Native applications. Understanding how dependency arrays and cleanup functions work ensures your components behave predictably and avoid common bugs like memory leaks.

