React Hooks

useEffect Hook

  • Run first time and every renders
import { useState, useEffect } from 'react';

const Home = () => {

  const [counter, setCounter] = useState(0)

  useEffect(() => {
    console.log("Run on every render")
  })

  const handleClick = () => {
    setCounter(counter + 1)
  }
  
  return (
    <>
      <h1>This Is A Counter</h1> 
      <button type='button' onClick={handleClick}>Click</button>  
      <p>{counter}</p> 
    </>
  )
}

export default Home;
  • Run first time only
useEffect(() => {
    console.log("Run on first render")
  }, [])
  • Run first time and state change
useEffect(() => {
    console.log("Run on every render")
  }, [counter])
  • Run on every renders but not the first render
const mount = useRef(false)

  useEffect(() => {
    if (mount.current) {
      console.log("Do not run on first render")
    } else {
      mount.current = true
    }
  }, [counter])
  • Run once but not on the first render

(to be continued)