Hamburger Icon
  • Labs icon Lab
  • Core Tech
Labs

Guided: Custom Hooks and Effects in React

Making your React-based code reusable is a key to minimizing development effort. Utilizing both effects and custom hooks help you accomplish this.

Labs

Path Info

Level
Clock icon Intermediate
Duration
Clock icon 24m
Published
Clock icon Jul 10, 2024

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    Introduction

    In this lab, you'll be updating a React Counter component to update the document title (which appears in the text of the browser tab) whenever a counter is updated.

    To do this you will utilize useEffect and then make your code reusable across various components by extracting it into a custom hook you will call useDocumentTitle. In this way you'll learn how and when to use useEffect, and how to create custom hooks.

    The lab has already setup a React project, and you can find the Counter component inside components/Counter.js.

    You will need to have the app opened in a separate browser tab so that you can see the document title in the text of the tab. Whenever you see this link: Go to your app, you can click it open the app in a new browser tab.

    Let's begin!

  2. Challenge

    Step 1: Set the Document Title

    In this first step of this lab, you will use the standard DOM APIs to update the title of the page. A simple React application is already in place with a TODO comment in the src/components/Counter.js file.

    The app provides two buttons: one "Toggle Color", defined in the src/App.js file, toggles a CSS class, storing the value in useState. The other button "Increment", defined in src/components/Counter.js, increments a counter, whose value is also stored in useState.

    To run the app:

    1. Click Run in the bottom right of the Terminal.
    2. Run the app by the following link: Go to your app When you go to your app, and you look in the developer console, you will notice that "Updating Title" prints every time that your Counter function is called (i.e. React "re-renders" the component).

    That's because React calls our functions over and over, every time state changes. In this case both when the counter is incremented and when the color is toggled (since Counter is a child of App).

    But the title doesn't need to be updated unless the counter was updated. In the next steps we will work on fixing this performance problem.

    NOTE: You can view the full solution to this step in the file solutions/step-01/Counter.js.

  3. Challenge

    Step 2: Add an Effect

    In this step, you will wrap your document title updating code in an "effect".

    Effects in React are a way to keep things that React doesn't automatically control in sync with the things React does control. For example React is controlling the DOM showing the total of your counter, but React isn't directly updating the document title. If you go to your app (don't forget to click Run in the terminal if you haven't already), and look in the developer console, you'll see that the code inside our effect is still running over and over, no matter which button you click.

    The performance problem, where the title is being updated more than necessary (i.e. the browser is doing more work than necessary) is still there. However, you've organized the code correctly, since you are keeping the document title in sync with the work React is doing. That's what useEffect is for!

    A benefit now will be that you can improve the performance of our application using other useEffect features. That's in the next step.

    NOTE: You can view the full solution to this step in the file solutions/step-02/Counter.js.

  4. Challenge

    Step 3: Add Dependencies

    In this step you will prevent the code inside your effect function from running when it doesn't need to.

    The useEffect function takes a second parameter. After the function you give it, it accepts an array of 'dependencies'. React will keep track of the items in that array and compare their values each time your component function is re-run. It will only re-run the effect if those dependencies have changed.

    In this way you are telling React "only run this effect the first time the function runs, and then after that only if the things in this array have changed."

    Remember you can go to your app (don't forget to click Run in the Terminal if you haven't already). Since the effect now only runs if counter changes, then it will not run when you click the Toggle Color button. That button updates state in App.js but doesn't change the value of counter, so there's no need to update the document title!

    The performance of your app has improved. You are only running code to keep things in sync when it actually needs to run.

    But what happens if the Counter component was ever unmounted (removed from the DOM and React's internal tree)? The Counter component should know what to do to keep things in sync. That's in the next step.

    NOTE: You can view the full solution to this step in the file solutions/step-03/Counter.js.

  5. Challenge

    Step 4: Add Cleanup Function

    In this step, you will ensure that your effect code cleans itself up. Remember, useEffect is for keeping things in sync that React does not control. But that means you also should deal with what happens if React removes our component from the DOM.

    React lets you do this by allowing you to return a function from the function you give useEffect. The function you return will be called by React if the component is ever 'unmounted', that is removed from React's tree of components due to logic.

    Remember you can go to your app (don't forget to click Run in the Terminal if you haven't already). You now have a complete useEffect that updates our document title. It would be nice to be able to reuse this logic across the application or even in other applications! How you can do that is the next step.

    NOTE: You can view the full solution to this step in the file solutions/step-04/Counter.js.

  6. Challenge

    Step 5: Create a Custom Hook

    In this last step, you will take the useEffect code and convert (or "extract") it into a reusable custom hook.

    A custom hook is really just a function that calls React hooks.

    Remember you can go to your app (don't forget to click Run in the Terminal if you haven't already). Now when you go to your app, you will see the document title update!

    That concludes this code lab! You now can use useEffect to keep things in sync that React doesn't control, improve performance by using the dependency array to tell React when to call your useEffect function, and make the logic reusable as a custom hook.

    Congratulations!

    NOTE: You can view the final full solution to this lab in the files solutions/step-05/useDocumentTitle.js and solutions/step-05/Counter.js.

Tony is a software architect, web application developer, database designer, and user experience designer with 15 years of experience. His experience has ranged across technologies such as HTML5, CSS3, ASP.NET MVC, Javascript, jQuery, AngularJS, KnockoutJS, LESS, Bootstrap, SQL, Entity Framework, and more.

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.