Can you explain how to use React hooks effectively?
React hooks are a powerful feature that let you use state and other React features without writing classes. Here are some tips for using them effectively:
Would you like me to explain any specific hook in more detail?
Yes, could you explain useCallback and useMemo in more detail? When should I use one over the other?
Both hooks help with performance optimization, but they serve different purposes:
useCallback memoizes functions to prevent unnecessary re-renders of child components that receive functions as props.
useMemo memoizes values to avoid expensive recalculations on every render.
Use useCallback when:
Use useMemo when:
Don't overuse these hooks! They come with their own overhead. Only use them when you have identified a genuine performance issue.
function ProfilePage({ userId }) { const [user, setUser] = useState(null); useEffect(() => { // This runs after render and when userId changes fetchUser(userId).then(userData => { setUser(userData); }); }, [userId]); return user ? <Profile user={user} /> : <Loading />;}// Without useCallback - a new function is created on every renderconst handleClick = () => { console.log(count);};// With useCallback - the function is only recreated when dependencies changeconst handleClick = useCallback(() => { console.log(count);}, [count]);// Without useMemo - expensive calculation runs on every renderconst sortedList = expensiveSort(items);// With useMemo - calculation only runs when items changeconst sortedList = useMemo(() => expensiveSort(items), [items]);