Don’t abuse the useEffect hook

Mushfiqur Rahman Niloy
2 min readJun 5, 2024

--

🔍 Understand the purpose of useEffect: The useEffect hook allows you to perform side effects in your components. It is ideal for integrating third-party outputs into the React render cycle. However, many developers misuse it for various purposes, which can lead to performance issues and laggy applications.

🔄 When does useEffect run? useEffect always runs after the component renders. This means any logic within useEffect that changes the state will trigger another render cycle. Therefore, it’s crucial to question whether you really need useEffect for your logic.

📋 Best Practices:

  1. Calculate state from existing state or props: Instead of using useEffect to derive new state from existing props or state, perform this calculation directly within your component. This avoids unnecessary state updates and re-renders.
  1. Avoid setting state from props within useEffect: Props are data that come from a parent component and are already managed by React. Using useEffect to update state based on props is redundant and inefficient. Instead, derive the necessary data directly from props in your JSX.

🔧 Helpful Tip: Always treat useEffect with caution and consider it a potential source of bugs if not used correctly. Ask yourself, “Do I really need useEffect here?” and explore alternatives before resorting to it.

Dan Abramov, one of the core developers of React, has excellent documentation explaining why “You may not need useEffect". It's worth a read to deepen your understanding.

Inspired by Bogdan Adrian’s book. Feel free to share your thoughts and experiences with useEffect in the comments! Let’s learn together and write more efficient React code. 🚀

--

--

Mushfiqur Rahman Niloy
Mushfiqur Rahman Niloy

Written by Mushfiqur Rahman Niloy

Front-End Lead @ Technovative Solutions LTD | Javascript, Typescript, Reactjs, Nextjs, React Query, Redux, Tailwindcss | Focused on DPP & DBP

No responses yet