How to use useEffect React hook

Find out what the useEffect React hook is for and how to use it!

Look at mineIntroduction to React hooksFirst of all, if you are a novice to them.

One of the React hooks I sometimes use isuseEffect.

import React, { useEffect } from 'react'

A very important function of hooks is to allow functional components to access lifecycle hooks.

Using class components, you cancomponentDidMount,componentWillUnmountwithcomponentDidUpdateEvents, these events will be used in many use cases, from variable initialization to API calls to cleanup.

Hook offeruseEffect()API. The call accepts a function as a parameter.

This function runs when the component is first rendered and every subsequent re-render/update. React first updates the DOM, and then the call is passed touseEffect(). Unlike the old version, all of these will not block UI rendering, even when blocking codecomponentDidMountwithcomponentDidUpdate, Which makes our app feel faster.


const { useEffect, useState } = React

const CounterWithNameAndSideEffect = () => { const [count, setCount] = useState(0) const [name, setName] = useState(‘Flavio’)

useEffect(() => { console.log(Hi </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">name</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> you clicked </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">count</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> times) })

return ( <div> <p> Hi {name} you clicked {count} times </p> <button onClick={() => setCount(count + 1)}>Click me</button> <button onClick={() => setName(name === ‘Flavio’ ? ‘Roger’ : ‘Flavio’)}> Change name </button> </div> ) }

ReactDOM.render( <CounterWithNameAndSideEffect />, document.getElementById(‘app’) )

the samecomponentWillUnmountThe work can be done optionally byreturnFeatures from ususeEffect()range:

useEffect(() => {
  console.log(`Hi ${name} you clicked ${count} times`)
  return () => {

useEffect()It can be called multiple times, which is a good separation of irrelevant logic (things that plague the life cycle events of class components).

sinceuseEffect()The function will run in each subsequent re-rendering/update. To improve performance, we can tell React to skip the run by adding a second parameter, which is an array containing the state variables to be observed. If one item in this array changes, React will only rerun the side effects.

  () => {
    console.log(`Hi ${name} you clicked ${count} times`)
  [name, count]

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

useEffect(() => {
  console.log(`Component mounted`)
}, [])

useEffect()Very suitable for adding logs, accessing third-party APIs, etc.

Example on Codepen:

Look at the penSide effects of React Hooks example #3By Flavio Copes (@flaviocopes) InCipher pen.

Tech Wiki Online!