1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Useeffect Hook
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
00Hrs
19Mins
41Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Useeffect Hook

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
19Mins
41Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useEffect Hook

Overview

React Components are essentially mathematical functions: data (props/state) goes in, and UI (JSX) comes out. This rendering calculation must be Pure, meaning it should never interact with the outside world during the calculation phase.

However, real applications must interact with the outside world. You need to fetch data from a server, start a timer, manually alter the DOM (like focusing an input), or subscribe to a WebSocket. These actions are called Side Effects.

The useEffect Hook is React's designated escape hatch. It allows you to safely execute side effects after React has successfully painted the UI to the browser screen. This ensures that slow side effects (like a 3-second API call) do not block the browser from immediately displaying the UI to the user.

Syntax

Basic useEffect Syntax
javascript
import { useState, useEffect } from 'react';

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

  // 1. React renders the UI first (returns the JSX)
  // 2. The browser paints the screen
  // 3. React executes this useEffect block
  useEffect(() => {
    // A Side Effect: Manipulating the browser's Document API
    document.title = `You clicked ${count} times`;
  }); // Notice the missing array here! (We will cover this next)

  return <button onClick={() => setCount(count + 1)}>Click Me</button>;
}

Common Pitfalls

  • Putting Side Effects in the Main Body: NEVER run an API fetch or manipulate the DOM directly inside the main body of your component. React will execute that code every single time the component re-renders (which can happen dozens of times per second). This leads to infinite loops and crashes.

Interview Questions

What is a 'Pure' function and why must React's render phase be pure?

A pure function always returns the exact same output for the same input and produces no side effects. React requires the render phase to be pure so it can safely pause, abort, or restart renders (especially with React 18's Concurrent Mode) without accidentally mutating data on the server or in the browser DOM.

When exactly does the code inside useEffect run?

The callback function inside useEffect runs asynchronously after the render is committed to the screen. This guarantees that your side effect does not block the browser from painting the visual UI for the user.

Real-World Example

Focusing an Input on Load: Autofocusing an input requires direct manipulation of the DOM. You cannot do this while React is calculating the Virtual DOM; it must happen in a useEffect after the real input element actually exists on the screen.

example
javascript
function SearchBar() {
  const inputRef = useRef(null);

  // We want the cursor to automatically focus in the search bar when the page loads
  useEffect(() => {
    // This is a side effect because we are manually touching the DOM API
    inputRef.current.focus();
  }, []);

  return <input ref={inputRef} placeholder="Search..." />;
}

Check Your Knowledge

Test your understanding of useEffect Hook with these quick questions.

Question 1

Which of the following operations is considered a 'Side Effect' in React?

Question 2

When is the code inside a `useEffect` callback actually executed?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useEffect Hook

Overview

React Components are essentially mathematical functions: data (props/state) goes in, and UI (JSX) comes out. This rendering calculation must be Pure, meaning it should never interact with the outside world during the calculation phase.

However, real applications must interact with the outside world. You need to fetch data from a server, start a timer, manually alter the DOM (like focusing an input), or subscribe to a WebSocket. These actions are called Side Effects.

The useEffect Hook is React's designated escape hatch. It allows you to safely execute side effects after React has successfully painted the UI to the browser screen. This ensures that slow side effects (like a 3-second API call) do not block the browser from immediately displaying the UI to the user.

Syntax

Basic useEffect Syntax
javascript
import { useState, useEffect } from 'react';

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

  // 1. React renders the UI first (returns the JSX)
  // 2. The browser paints the screen
  // 3. React executes this useEffect block
  useEffect(() => {
    // A Side Effect: Manipulating the browser's Document API
    document.title = `You clicked ${count} times`;
  }); // Notice the missing array here! (We will cover this next)

  return <button onClick={() => setCount(count + 1)}>Click Me</button>;
}

Common Pitfalls

  • Putting Side Effects in the Main Body: NEVER run an API fetch or manipulate the DOM directly inside the main body of your component. React will execute that code every single time the component re-renders (which can happen dozens of times per second). This leads to infinite loops and crashes.

Interview Questions

What is a 'Pure' function and why must React's render phase be pure?

A pure function always returns the exact same output for the same input and produces no side effects. React requires the render phase to be pure so it can safely pause, abort, or restart renders (especially with React 18's Concurrent Mode) without accidentally mutating data on the server or in the browser DOM.

When exactly does the code inside useEffect run?

The callback function inside useEffect runs asynchronously after the render is committed to the screen. This guarantees that your side effect does not block the browser from painting the visual UI for the user.

Real-World Example

Focusing an Input on Load: Autofocusing an input requires direct manipulation of the DOM. You cannot do this while React is calculating the Virtual DOM; it must happen in a useEffect after the real input element actually exists on the screen.

example
javascript
function SearchBar() {
  const inputRef = useRef(null);

  // We want the cursor to automatically focus in the search bar when the page loads
  useEffect(() => {
    // This is a side effect because we are manually touching the DOM API
    inputRef.current.focus();
  }, []);

  return <input ref={inputRef} placeholder="Search..." />;
}

Check Your Knowledge

Test your understanding of useEffect Hook with these quick questions.

Question 1

Which of the following operations is considered a 'Side Effect' in React?

Question 2

When is the code inside a `useEffect` callback actually executed?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A