乐闻世界logo
搜索文章和话题

Prevent useEffect to fire on initial render

1个答案

1

In React, useEffect by default executes after the initial render and on every subsequent update. To prevent useEffect from triggering during the initial render, you can specify a dependency array and include a state or prop to control its execution timing.

Example:

Consider a component where you want to fetch user information when the prop userId changes, but not during the initial render. You can implement it as follows:

jsx
import React, { useEffect, useState } from 'react'; function UserProfile({ userId }) { const [user, setUser] = useState(null); useEffect(() => { const fetchUser = async () => { const response = await fetch(`https://api.example.com/users/${userId}`); const userData = await response.json(); setUser(userData); }; // Only execute when `userId` changes if (userId) { fetchUser(); } }, [userId]); // The dependency array specifies `userId` return ( <div> {user ? ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> ) : ( <p>Loading user...</p> )} </div> ); }

In this example, useEffect has a dependency array containing userId, meaning the code inside will only execute when userId changes. Since userId typically does not change during the initial render (assuming it is passed from a parent component and is not undefined initially), the code inside useEffect will not trigger during the initial render. If userId is undefined or may receive a value after the initial render, you should add checks such as if (userId) in the code to avoid unnecessary operations when userId is invalid.

2024年6月29日 12:07 回复

你的答案