arrow_backBACK TO DRILLS
Blue Beltcustom-hooksPREMIUM
You Cannot Await One Custom Hook Inside Another Hook
A developer wants to fetch a user's profile with one custom hook, then use the returned data to fetch that user's posts with a second custom hook.
REACT_MODULE // 0x42
function useProfile(userId) {
const [profile, setProfile] = useState(null);
useEffect(() => {
fetchProfile(userId).then(setProfile);
}, [userId]);
return profile;
}
function usePosts(profile) {
const [posts, setPosts] = useState([]);
useEffect(() => {
if (profile) fetchPosts(profile.id).then(setPosts);
}, [profile]);
return posts;
}
function ProfilePage({ userId }) {
const profile = useProfile(userId);
const posts = usePosts(profile);
return <div>{posts.length} posts</div>;
}Why does this pattern work correctly instead of requiring the developer to await one hook before calling the next?