useEffect in Hooks

useEffect in Hooks

What is useEffect Hooks?

If you are familiar about with react life cycle method of class component, you can compare useEffect Hook as componentDidMount, componentDidUpdate and componentWillUnmount combined

How to use useEffect Hook:-

  • First you have to import it from react.

  • import {useEffect} from 'react';

  • we have to place this useEffect() hook inside the function component.

  • When we place useEffect() hook inside the function component then we have the access of props and state easily.

  • useEffect run after first render and also after every render update.

useEffect Hook:-

  1. useEffect aceepts two arguments. The second argument is optional.

    Ex: - useEffect(<function> , <dependency)

  2. The function inside useEffect() will run after every render is commited.

  3. second argument of useEffect is the array of values which depends on effects.

  4. IMPORTANT NOTE:- you can call useEffect hook as many times as you need.

function User() {
  let [count, setCount] = useState(0)
  useEffect(() => {
    console.log("hi I am Effect...")
  })
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Update</button>
    </div>
  )
}

second argument of useEffect is the array of values which depends on the function component.

RUN ONES:- if you want to run useEffect only one time when web is render first on screen so write empty [] .

function User() {
  let [count, setCount] = useState(0)
  useEffect(() => {
    console.log("hi I am Effect..." + count)
  },[] )
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Update</button>
    </div>
  )
}

RUN WHEN COUNT CHNAGE:-

when count update, useEffect run also run this time.

function User() {
  let [count, setCount] = useState(0)
  useEffect(() => {
    console.log("hi I am Effect..." + count)
  },[count] )
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Update</button>
    </div>
  )
}

HAPPY LEARNING...