useEffect is a React Hook used in React Native to handle side effects such as API calls, subscriptions, timers, and lifecycle-related logic inside functional components. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
The useEffect hook accepts two arguments:
// Basic useEffect syntax
useEffect(() => {
console.log("Effect executed");
}, []);
// useEffect running once on component mount
import React, { useEffect } from "react";
import { View, Text } from "react-native";
const App = () => {
useEffect(() => {
console.log("Component Mounted");
}, []);
return (
<View>
<Text>Hello React Native</Text>
</View>
);
};
export default App;
When the component loads for the first time, the message "Component Mounted" is printed in the console. Because the dependency array is empty, the effect runs only once.
Click the buttons below to visualize how useEffect behaves when a component mounts, updates its state, and unmounts.
If you start a Timer in useEffect but forget to clear it in the return function, the timer keeps running even after the component is removed. This is a Memory Leak.
// Demonstrating mount, update, and unmount behavior
useEffect(() => {
console.log("Mounted or Updated");
return () => {
console.log("Component Unmounted");
};
}, [count]);