Kibo UI
Grid

AI Chatbot

Use Kibo UI components to create a fully featured AI chatbot interface.

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

  1. Only call hooks at the top level of your component or custom hooks
  2. 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

JavaScriptindex.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

useCallback vs useMemo

Both hooks help with performance optimization, but they serve different purposes:

useCallback

JavaScriptindex.js
useCallback
memoizes functions to prevent unnecessary re-renders of child components that receive functions as props.

JavaScriptindex.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

JavaScriptindex.js
useMemo
memoizes values to avoid expensive recalculations on every render.

JavaScriptindex.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.