Senior
When does the useEffect callback trigger? What phases are there in React?
sobes.tech AI
Answer from AI
useEffect runs after React has rendered the component and updated the DOM. This means that the callback inside useEffect executes after the 'commit' phase (applying changes to the DOM).
Phases in React:
- Render phase — React calculates what needs to be rendered and creates the virtual DOM. Side effects should not be called here.
- Commit phase — React applies changes to the real DOM and runs effects.
useEffect runs after the commit phase, allowing safe execution of side effects such as API requests, subscriptions, and DOM manipulations.
Example of using useEffect:
import React, { useEffect, useState } from 'react';
function Example({ userId }) {
const [userData, setUserData] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => setUserData(data));
}, [userId]); // effect triggers when userId changes
return <div>{userData ? userData.name : 'Loading...'}</div>;
}
Here, the effect will run after rendering and update the state, which will trigger a re-render with the new data.