Lifecycle - useEffect
by Tomas Trescakยท Advanced React

Root Folder
Not Attempted
NameProgress
Introduction
Not Read
๐Ÿฐ Player
Not Read
Setup
Not Attempted
NameProgress
Software Installation
Not Read
Project Setup
Not Read
Running and Testing
Not Read
React and ReactDOM
Not Read
๐Ÿ’ก Assignment 1: Welcome Message
Not Attempted
Submissions
Not Read
React
Not Attempted
NameProgress
JSX and Components
Not Read
Props
Not Read
๐Ÿ‘พ Exercise: Props
Not Attempted
CSS Styles
Not Read
useState and Hooks
Not Read
๐Ÿ‘พ Exercise: useState
Not Attempted
Conditional Rendering
Not Read
Lists
Not Read
๐Ÿ‘พ Exercise: Lists
Not Attempted
Forms and Events
Not Read
๐Ÿ‘พ Exercise: Forms
Not Attempted
๐Ÿ’ก Assignment 2: Front End
Not Attempted
Pure Components - memo
Lifecycle - useEffect
Expensive? - useMemo
DOM Interactions - useRef
forwardRef
useImperativeHandle
๐Ÿ‘พ useImperativeHandle
Not Attempted
Context
useCallback
useId
useReducer
Infrastructure
Not Attempted
NameProgress
Database
Not Read
NextAuth and Github Authentication
Not Read
Prisma and ORM
Not Read
Project Setup
Not Read
Project Authentication
Not Read
APIs
Not Attempted
NameProgress
APIs
Not Read
APIs - Slides
Not Attempted
Rest APIs
Not Read
Rest APIs - Express.js
Not Read
ReastAPIs - Next.js
Not Read
Securing APIs
Not Read
Securing APIs - NextAuth
Not Read
tRPC
Not Attempted
NameProgress
tRPC
Not Read
tRPC - Routers
Not Read
tRPC - Server Rendering
Not Read
tRPC - Client Rendering
Not Read
Persisting Data
Not Read
Assignment 3: APIs
Not Read
0 / 300 XP

Lecture Transcript
If you prefer text to video, check out the transcript of the presentation above

Let's explore the lifecycle of a React component and to use it to your advantage!

To explain the lifecycle of a React component, we'll break it down into three phases

During the mounting phase, the component is first rendered and committed to the browser. At this stage, all HTML is visible to the user. After committing, a callback is called.

During the updating phase the component re-renders due to state or prop changes. This process has three phases. First, a cleanup after the previous update is performed. Then, the component is rendered and then the changes are committed to DOM.

During the unmounting phase, the component is removed from the DOM, performing the cleanup. Let's break it down using an example!

Let's consider a simple component that renders a count value and a button that changes the count value. Note that the count value is rendered in the p element.

We can show or hide this component by clicking the Toggle button.

We also create a helper function getCount, that returns the value rendered in the p element, or null, if the p element does not exist.

Now, we see several logs in the console. The first message shows that the component is rendering, and the p element showing the count value does not exist. This is correct, as during this phase, the rendering is done in React's VDOM, and nothing has been committed or rendered in the browser.

We will now use useEffect hook to render a message when this component initially renders into your browser.

Particularly, note that the second message in the console shows that the component has been mounted and that the value in the p element shows the correct value! At this stage everything is rendered in the dom.

The useEffect comes equipped with a dependency array and executes only variables provided in this dependency array change. Since nothing is provided to this array, the useEffect only executes once when the component is mounted and unmounted.

We also have another useEffect hook that tracks changes in the count variable and executes only when the count changes. You can see the message in the console with the value of the count variable.

Note the use of the count variable in the dependency array of this hook.

Now, take a look at what happens when we click on the Increment button. First, we see that the component started to render, and the p element still shows the old value.

Then, we clean up after a previous update. The cleanup function is returned from the useEffect hook and executes prior to next commit or unmount. This time, we only logged a message that the cleanup is performed.

Then, the react changes are committed, and a new count value is displayed to the user.

Last, we hide the component by clicking on the Toggle button. Similarly, to clean up after the update of the count state variable, we return the cleanup function from the useEffect with no dependencies.

Last, we also see that the cleanup of the last update is performed.

Consider this example, where we define a custom hook that fetches data from an external API. Please study this example and try to explain how we used the useEffect hook to our advantage, particularly the request cancellation procedure using isCancelled. Think why is it essential to set isCancelled to true and what could happen if you would not do that. Leave a comment below!

Description
All the extra information about this section

React Functional Component Lifecycle with <strong>useEffect</strong>

React lifecycle events for functional components are managed using useEffect, which can mimic the behavior of lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount from class based React components.


Visual Overview

Phases of the Lifecycle

  1. Mounting: The component is first rendered.
  2. Updating: The component re-renders due to state or prop changes.
  3. Unmounting: The component is removed from the DOM.

Here's a flowchart to visualize the lifecycle in functional components:

  1. Render Phase:
    • React renders the component.
  2. Commit Phase:
    • React applies DOM updates.
    • useEffect runs after rendering.
  3. Cleanup (when applicable):
    • Cleanup functions in useEffect run before the component unmounts or re-renders.

Example Code

Letโ€™s demonstrate these lifecycle phases using useEffect:

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

const LifecycleDemo = () => {
  const [count, setCount] = useState(0);

  // Runs only once when the component is mounted
  useEffect(() => {
    console.log("Component mounted");

    // Cleanup: Runs when the component unmounts
    return () => {
      console.log("Component unmounted");
    };
  }, []); // Dependency array is empty, so it runs only on mount and unmount.

  // Runs every time 'count' changes
  useEffect(() => {
    console.log(`Count updated to ${count}`);

    // Cleanup: Runs before the next effect or on unmount
    return () => {
      console.log(`Cleanup before count changes or unmount: ${count}`);
    };
  }, [count]); // Dependency array has 'count', so it runs when 'count' changes.

  return (
    <div>
      <h1>React Lifecycle with useEffect</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default LifecycleDemo;

Graph for Lifecycle Events

  1. Mounting:
    • useEffect(() => { ... }, [])
  2. Updating:
    • useEffect(() => { ... }, [dependencies])
  3. Unmounting:
    • Cleanup function inside useEffect.
Maggie

Discuss with Maggie
Use the power of generative AI to interact with course content

Discussion

0 comments
Loading editor ...
Remember to be polite and report any undesirable behaviour

Category

Empty

Labels

Discussion has no labels

1 participant

user avatar

Priority

Notifications

You're not receiving notifications from this thread.
Course Outline