Sitemap
Audrey Chipman

Audrey Chipman

UseEffect() in React

5 min readAug 2, 2024

--

React is a powerful JavaScript library for building user interfaces. One of React’s most essential hooks is ‘useEffect’. This hook plays a critical role in handling side effects in functional components. Understanding how to use the ‘useEffect’ hook can make a huge difference in your React app, and in your life as a programmer. In this post, we will take a look at ‘useEffect’ very closely.

Press enter or click to view image in full size
Source below as useEffect diagram

What is useEffect? Also, what are side effects?

The ‘useEffect’ hook is a hook provided by React. This hook lets you perform side effects in functional components. Side effects are tasks that can affect other components and often involve tasks that can’t be done while rendering. A list of side effects included below:

Side effects include tasks such as:

  • Data Fetching: Retrieving data from a server.
  • Subscriptions: Setting up real-time subscriptions or WebSocket connections.
  • Manual DOM Manipulation: Changing the DOM outside of the React render cycle.
  • Timers: Setting up intervals or timeouts.
  • Logging: Writing logs or analytics data.

Before hooks, side effects were typically handled in class components with lifecycle methods like, ‘componentDidMount’ or ‘componentDidUpdate’. The ‘useEffect’ hook is way better and easier to use. This hook allows us to improve functionality to function components, simplify component logic, and allow for better code reuse. Fun Fact: The ‘useEffect’ hook is most commonly used while fetching data!

Syntax for ‘useEffect’:

UseEffect takes two arguments, an effect callback and a dependency array(if needed).

How do the effect callback and dependency array work in ‘useEffect’?

Effect Callback: The effect callback is executed after the component renders. This function can contain any code that performs a side effect.

Dependency Array: The dependency array helps React determine when to run the effect callback. The dependency array is an optional second argument and is needed if you have specifics of when the effect callback should run. The dependency array behavior varies depending on the content of the array.

Basic Usage of the ‘useEffect’ hook:

This image shows the ‘useEffect’ hook can be used while fetching data when a component mounts.

Press enter or click to view image in full size
Image provided by Chat GPT

When to use the different types of dependency arrays…

  • Empty Array ([]): The effect callback runs only once after the initial render, similar to ‘componentDidMount' in class components.
  • No Dependency Array: The effect callback runs after every render, similar to ‘componentDidUpdate' in class components.
  • Non-Empty Array: The effect callback runs only when one or more dependencies change. You can have multiple argumets.

Common Uses for the ‘useEffect’ hook:

Data Fetching

Fetching data from an API is a common use for the 'useEffect'. By specifying an empty dependency array, you ensure that the fetch operation occurs only once.

Synchronizing State with Props

If you need to synchronize a component’s internal state with changes to its props, look no further.

Setting Up and Cleaning Up Subscriptions

When dealing with subscriptions or timers, you can set them up in the ‘useEffect' hook and clean them up to avoid memory leaks.

Common Mistakes while using ‘useEffect’ and how to prevent them

  • Infinite Loops:

Issue: Incorrectly specifying dependencies can cause infinite loops. For example, if you include a state that is updated inside the effect, it can trigger the effect continuously.

Get Audrey Chipman’s stories in your inbox

Join Medium for free to get updates from this writer.

Solution: Carefully specify dependencies and ensure they don’t cause the effect to run endlessly.

  • Updating State in Effect: When updating state within 'useEffect', ensure that it doesn’t cause unnecessary re-renders. This is particularly important when updating state based on props or other state variables.

Issue: Updating state in 'useEffect’ without considering the impact can lead to unnecessary re-renders.

Solution: Ensure that state updates inside 'useEffect’ do not lead to excessive renders or infinite loops.

  • Avoiding Side Effects in Render: Ensure that side effects are only performed inside ‘useEffect' and not during rendering. This keeps rendering predictable and side-effect free.

Issue: Performing side effects directly during rendering can lead to unpredictable behavior.

Solution: Always use ‘useEffect' for side effects. This ensures that side effects are managed after the render phase, keeping the rendering predictable.

  • Debouncing and Throttling: When dealing with user inputs or high-frequency events, consider debouncing or throttling to reduce the frequency of effect executions.

Issue: High-frequency events, such as user input, can cause ‘useEffect' to run too often.

Solution: Use debouncing or throttling techniques to limit the frequency of effect executions.

  • Proper Cleanup: Always return a cleanup function if your effect involves subscriptions or timers to avoid memory leaks.

Issue: Failure to clean up subscriptions, timers, or other side effects can lead to memory leaks.

Solution: Return a cleanup function from the effect callback to properly handle cleanup.

Conclusion

The ‘useEffect' hook is an essential tool for managing side effects in functional React components. Understanding its syntax, behavior, and best practices can significantly enhance the performance and reliability of your React applications. By mastering the ‘useEffect’ hook, you gain greater control over how and when side effects are executed, allowing you to build more efficient and effective React components.

Whether you’re fetching data, synchronizing state with props, or managing timers, ‘useEffect' provides a flexible and powerful mechanism to handle side effects in your functional components. By following best practices and avoiding common pitfalls, you can leverage ‘useEffect' to build more robust and performant applications.

Sources

useEffect Diagram-

Djirdeh, Hassan. “A Breakdown of the React USEEFFECT Hook.” Telerik Blogs, Telerik, 31 Jan. 2023, www.telerik.com/blogs/breakdown-react-useeffect-hook

--

--