DEV Community

Abdusanadzoda Abdulaziz
Abdusanadzoda Abdulaziz

Posted on

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.

Top comments (0)