How to call a method when component is rendered for the first time in React?
Use useEffect with an empty dependency array to run code once when the component mounts.
intermediateState lifecyclereactuseEffectlifecyclemount
Published: 10/26/2025
Updated: 10/26/2025
Question
How to call a method when a component is rendered for the first time in React?
Answer
In React functional components, you use useEffect with an empty dependency array ([]) to mimic “on mount” behavior.
import { useEffect } from 'react';
function Dashboard() {
useEffect(() => {
console.log('Component mounted');
fetchData(); // your method here
}, []);
const fetchData = () => {
console.log('Fetching data...');
};
return <h2>Welcome to Dashboard</h2>;
}
âś… How it works:
useEffectruns after the first render.- Empty dependency
[]ensures it runs only once.
Real-World Example
- Fetching API data on component load.
- Setting up event listeners.
- Running initial analytics or logs.
Quick Practice
Build a component that fetches user data from an API once when it mounts.
Summary
To run logic once on mount, use useEffect(() => {...}, []).
Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions
How do I mimic componentDidMount in functional components?
By using useEffect with an empty dependency array.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.