What’s a UseEffect, Do You Like It? [Part 1]

You are going to learn about Captain America of React 🤪

What’s a UseEffect, Do You Like It? [Part 1]

If you are using REACT and haven't understood the useEffect hook then you are not alone :).

Takeways

  • 🤔 what is rendering or render and how its work.
  • 🤔 what is side-effects
  • 🤔 what is useEffect hook and how its work.
  • 🤔 Lifecycle methods using useEffect.

Before we talk about effects, we need to talk about rendering.

Rendering

Rendering is a process when a component or element rendered into the root DOM node. Note : a component is a group of elements

DOM Example: DOM IMAGE.png (source codecademy.com)

Example:

//Html file

<div id="root"></div>

//React component
function App() {
  const [count, setCount] = useState(0); //state

  return (
    <div>
      <p>Hello World</p>
    </div>
  );
}

ReactDOM.render(App, document.getElementById('root'));
  • In the above example, we are rendering our App component into the DOM where the id is root by using ReactDOM.render method. It takes two arguments one is the component we are rendering and the second the root DOM node.

Re-rendering

Whenever the state of the component is changed the react-dom updates the browserdom thus the re-rendering of the react component happens because the dom is updated now.

let's take an example:

function App() {
  const [count, setCount] = useState(0); //state

  const clickHanlder = () => {     // Hanlder function
    setCount(count + 1);
  };
 console.log(` ${count} times rendered`); 

  return (
    <div>
      <p>{count}</p>
      <button onClick={clickHanlder}>click me</button>
    </div>
  );
}

ReactDOM.render(App, document.getElementById('root'));
  • in the above example, we have a count state and we have a click handler function. whenever we click on the button click me the console.log() triggered because whenever the click me button trigger reactDOM.render method will update the dom. So It will basically show you how many times the components re-rendering.

note : If you are using the above example , then you will see first 0 times rendered because the first rendering of the component.

Side-effects

whenever we want to use anything which is outside of the react components, it is known as side-effects. Examples of side-effects are using local storage, fetch requests, manipulating DOM directly, using timer functions like setTimeout(), and many more.

const App= () => {
  document.title = "hello world"; // Side-effect!
  return <div>Hello World</div>;
};
  • in the above example, we are accessing the DOM element and it's an example of a side-effect.

Use-effect

use-effect manages side effects and react component lifecycle methods in the functional component. Another definition is

The Effect Hook lets you perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

useEffect() hooks accept 2 arguments:

useEffect(callback,[ dependencies])

the callback is the callback function containing side-effect logic. useEffect() executes the callback function after first rendered or first screen paint 😇 .

dependencies is an optional array of dependencies. useEffect() executes callback only if the dependencies have changed between renderings.

Dependencies

  • Not provided: the side-effect runs after every rendering.

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Runs after every rendering
  });  }
  • An empty array []: the side-effect runs once after the initial rendering.
import { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Runs ONCE after initial rendering
  }, []);}
  • Has props or state values [prop1, prop2, ..., state1, state2] : it will run when any depenendecy value changes.
import { useEffect, useState } from 'react';

function App({ prop }) {
  const [state, setState] = useState('');
  useEffect(() => {
    // Runs ONCE after initial rendering
    // and after every rendering ONLY IF `prop` or `state` changes
  }, [prop, state]);}

Using Example of side-effect

example:

import { useEffect } from "react";

const App = () => {

  useEffect(() => {
    document.title = "Hello World"; //accessing dom title
  });
  return <>Hello World</>;

};

// this useEffect will re-run on every re-rendering

in the above example, we are accessing the DOM element and it's an example of a side-effect.

Component DidMount and DidUpdate using useEffect.

  • Component DidMount

  • To invoke use-effect only once after the first render use empty dependency array []:

const App = () => {

  useEffect(() => {
    document.title = "Hello World"; //accessing dom title
  },[ ]);
     return <>Hello World</>;
}
  • Component DidUpdate

  • whenever we are using any props or state in our effect we have to pass it as a dependency argument in order to trigger the effect whenever the value of dependency changed.
  • Using the dependencies argument of useEffect() you control when to trigger or invoke the side-effect.
const App = () => {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    document.title = `useEffect Triggered ${counter}`;
  }, [counter]);

  return (
    <div>
      <p>{counter}</p>
      <button onClick={() => setCounter(counter + 1)}>click me</button>
    </div>
  );
};

in the above example whenever the value of count changed the use effect triggered after the initial rendering .

NOTE

I hope you find this article useful and enjoyed it while reading it. Be ready for the next part of this series. In the next article, I will cover the cleanup function in use effect and how use effect different from classes' lifecycle method.

Till Then Show some Love 😍 and say no to racism✊