AI Chatbot
Use Kibo UI components to create a fully featured AI chatbot interface.
Powered by
Ha
Can you explain how to use React hooks effectively?
Op
React Hooks Best Practices
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:
Rules of Hooks
- Only call hooks at the top level of your component or custom hooks
- Don't call hooks inside loops, conditions, or nested functions
Common Hooks
- useState: For local component state
- useEffect: For side effects like data fetching
- useContext: For consuming context
- useReducer: For complex state logic
- useCallback: For memoizing functions
- useMemo: For memoizing values
Example of useState and useEffect
index.js
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 />;}
Would you like me to explain any specific hook in more detail?
Ha
Yes, could you explain useCallback and useMemo in more detail? When should I use one over the other?
Op memoizes functions to prevent unnecessary re-renders of child components that receive functions as props.
memoizes values to avoid expensive recalculations on every render.
useCallback vs useMemo
Both hooks help with performance optimization, but they serve different purposes:
useCallback
index.js
useCallback
index.js
// 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]);
useMemo
index.js
useMemo
index.js
// Without useMemo - expensive calculation runs on every renderconst sortedList = expensiveSort(items);// With useMemo - calculation only runs when items changeconst sortedList = useMemo(() => expensiveSort(items), [items]);
When to use which?
-
Use useCallback when:
- Passing callbacks to optimized child components that rely on reference equality
- Working with event handlers that you pass to child components
-
Use useMemo when:
- You have computationally expensive calculations
- You want to avoid recreating objects that are used as dependencies for other hooks
Performance Note
Don't overuse these hooks! They come with their own overhead. Only use them when you have identified a genuine performance issue.