RG

Hey everyone,

I'm trying to get a solid grasp on React Hooks, specifically `useState` and `useEffect`. I've been reading the documentation, but sometimes seeing practical examples really helps solidify the concepts.

For instance, when would you typically choose `useEffect` over setting state directly? What are some common pitfalls to avoid?

Here's a small example I've put together:


import React, { useState, useEffect } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // This effect runs after every render
    document.title = `You clicked ${count} times`;
    console.log('Effect ran!');

    // Cleanup function (runs before the next effect or unmount)
    return () => {
      console.log('Cleanup running...');
    };
  }); // No dependency array, runs on every render

  return (
    

You clicked {count} times

); } export default Counter;

Any insights or other common use cases for hooks would be greatly appreciated!

Thanks!

JS

Great question, ReactGuru!

useEffect is crucial for handling "side effects" in your components – actions that interact with the outside world or don't directly relate to rendering the UI. Think:

  • Fetching data from an API
  • Setting up subscriptions (e.g., timers, event listeners)
  • Manually manipulating the DOM (though this should be rare with React)
  • Updating the document title (like your example!)

You use useEffect when you need to perform an action *after* the component has rendered, and potentially re-run it based on changes in dependencies.

A common pitfall is forgetting the dependency array. Without it (or with an empty array `[]`), your effect might run infinitely or more often than intended, leading to performance issues or unexpected behavior.

Your `Counter` example is a perfect use case for `useEffect` to update the document title. The cleanup function is also vital for preventing memory leaks, especially with subscriptions or event listeners.

Keep up the great work!

AP

To add to what JavaScriptDev said, remember that `useEffect` with an empty dependency array `[]` acts similarly to `componentDidMount` in class components, running only once after the initial render.

If you want it to run when specific state or props change, you include them in the array. For example:


useEffect(() => {
  // This effect runs only when 'userId' changes
  fetchUserData(userId);
}, [userId]); // Dependency array with userId
                            

This pattern is super powerful for managing data fetching efficiently.

Reply to this topic