useEffect Hook — A Practical Guide

Manikandan Balasubramanian
3 min readJun 24, 2024

useEffect is the one of the important hook in the React Hooks family. The useEffect hook is used to manage side effects in functional components, such as data fetching, DOM manipulation, and subscriptions. It takes a function and runs it after the component renders.

In this example, the effect runs once after the component’s initial render due to the empty dependency array. This is useful for actions that should only happen when the component is first mounted.

Dependency Array:

The dependency array determines when the effect should run. If any value in the dependency array changes between renders, the useEffect will be executed.

Using dependencies ensures that the effect is responsive to changes in the variables that matter. Omitting the dependency array would cause the effect to run after every render, which might lead to unnecessary or unintended behaviour.

Cleanup:

Perform cleanup to prevent or avoid memory leaks or unnecessary operations when the component unmount or when the effect dependencies change.

This is crucial when you’re setting up listeners, timers, or other subscriptions. The cleanup function is executed before the component unmount or before the effect runs again due to dependency changes.

Multiple Effects:

We can use multiple useEffect hooks in a single component for different purposes. This improves code readability and separates concerns.

By having multiple effects, you can keep our code organized and focused on specific tasks, making it easier to manage and maintain.

Avoid Redundant Effects:

When using useEffect, be cautious to avoid triggering redundant effects by updating the state within the effect that relies on the same dependency.

To avoid this, make sure that useEffect doesn’t directly modify the dependencies that it relies on.

Async in useEffect:

useEffect dependencies can be asynchronous values like promises or functions. This is particularly useful when you want to fetch data before running an effect.

By using a function that returns a promise, we ensure that the data fetching is asynchronous and completed before the effect is run.

Conclusion

The useEffect hook is a powerful tool for managing side effects in React functional components. By understanding and applying these tips and tricks, we can use useEffect more effectively and confidently in various scenarios, from simple data fetching to complex interactions and optimizations. Remember to always consider your component’s lifecycle and dependencies to achieve the desired behaviour in application.

Thanks for reading !!!

--

--

No responses yet