DEV Community

Abdusanadzoda Abdulaziz
Abdusanadzoda Abdulaziz

Posted on

2 2

How to use the useEffect React hook ๐ŸŽˆ

Find out what the useEffect React hook is useful for, and how to work with it!

One React hook I sometimes use is useEffect.

import React, { useEffect } from 'react'
Enter fullscreen mode Exit fullscreen mode

One very important feature of Hooks is allowing function components to have access to the lifecycle hooks.

Using class components you can register a function on the componentDidMount, componentWillUnmount and componentDidUpdate events, and those will serve many use cases, from variables initialization to API calls to cleanup.

Hooks provide the useEffect() API. The call accepts a function as argument.

The function runs when the component is first rendered, and on every subsequent re-render/update. React first updates the DOM, then calls any function passed to useEffect(). All without blocking the UI rendering even on blocking code, unlike the old componentDidMount and componentDidUpdate, which makes our apps feel faster.

Example:

const { useEffect, useState } = React

const CounterWithNameAndSideEffect = () => {
  const [value, setValue] = useState(0)

  useEffect(() => {
    document.title= `New messages(${value})`;
  })

  return (
        <>
          <h1>{value}</h1>
          <button className="btn"
                  onClick={() =>setValue (value+1)}>Inclease
          </button>
        </>
  )
}

ReactDOM.render(
  <CounterWithNameAndSideEffect />,
  document.getElementById('app')
)
Enter fullscreen mode Exit fullscreen mode

useEffect() can be called multiple times, which is nice to separate unrelated logic (something that plagues the class component lifecycle events).

Since the useEffect() functions are run on every subsequent re-render/update, we can tell React to skip a run, for performance purposes, by adding a second parameter which is an array that contains a list of state variables to watch for. React will only re-run the side effect if one of the items in this array changes.

useEffect(() =>{
       document.title= `New messages(${value})`;
}, [value]);
Enter fullscreen mode Exit fullscreen mode

Similarly you can tell React to only execute the side effect once (at mount time), by passing an empty array:

useEffect(() =>{
       document.title= `New messages(${value})`;
}, []);
Enter fullscreen mode Exit fullscreen mode

useEffect() is great for adding logs, accessing 3rd party APIs and much more.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Googleโ€™s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay