Hey everyone,
I've been diving deeper into React lately, and I'm trying to get a solid grasp on its core hooks: useState
, useEffect
, and useContext
. While I understand their basic functions, I'm looking for some clarification on best practices and common pitfalls.
useState
Deep DiveI understand useState
is for managing local component state. I've used it for simple things like toggling UI elements or managing form input values. Are there any advanced patterns or considerations I should be aware of, especially when dealing with complex state objects?
useEffect
useEffect
is powerful for handling side effects, like fetching data or setting up subscriptions. I'm particularly interested in understanding the dependency array correctly. What are the common mistakes people make with it, and how can I ensure my effects run only when necessary?
For example, when fetching data, I usually do something like this:
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUserData = async () => {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
setUser(data);
setLoading(false);
} catch (error) {
console.error("Failed to fetch user data:", error);
setLoading(false);
}
};
fetchUserData();
}, [userId]); // Dependency array
if (loading) {
return Loading user profile...;
}
if (!user) {
return User not found.;
}
return (
{user.name}
Email: {user.email}
);
}
Is this a good pattern? Should I be concerned about stale closures with async operations inside useEffect
?
useContext
useContext
seems like a great way to avoid prop drilling. I've experimented with it for theme management. What are some common use cases where useContext
is most beneficial? Are there performance implications to consider when using it extensively?
Any insights, code examples, or resources you recommend would be greatly appreciated!
Thanks in advance!