Implementing an Effect Hook in our blog app

Now that we have learned how the Effect Hook works, we are going to use it in our blog app, to implement the title changing when we log in/log out (when the user state changes).

Let's get started implementing an Effect Hook in our blog app:

  1. Edit src/App.js, and import the useEffect Hook:
import React, { useReducer, useEffect } from 'react'
  1. After defining our useReducer Hook and the state destructuring, define a useEffect Hook that adjusts the document.title variable, based on the username value:
    useEffect(() => {
  1. If the user is logged in, we set the document.title to <username> - React Hooks Blog. We use template strings for this, which allow us to include variables, or JavaScript expressions, in a string via the ${ } syntax. Template strings are defined using `:
        if (user) {
document.title = `${user} - React Hooks Blog`
  1. Otherwise, if the user is not logged in, we simply set the document.title to React Hooks Blog:
        } else {
document.title = 'React Hooks Blog'
}
  1. Finally, we pass the user value as the second argument to the Effect Hook, in order to ensure that whenever the user value updates, our effect function triggers again:
    }, [user])

If we start our app now, we can see that the document.title gets set to React Hooks Blog, because the Effect Hook triggers when the App component mounts, and the user value is not defined yet:

The effect of our Effect Hook: changing the web page title

After logging in with Test User, we can see that the document.title changes to Test User - React Hooks Blog:

The effect of our Effect Hook re-triggering, after the user value changes

As we can see, our Effect Hook re-triggers successfully after the user value changes!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.153.38