Logo


Useeffect in react

A functional React component uses props and/or state to calculate the output. If the functional component makes calculations that don't target the output value, then these calculations are named side-effects.We cannot stop the component renders ,So we have to limit our useEffect.useEffect accept two arguments 1- A callBack function and dependency arguments

1useEffect(callback[, dependencies]);

Useeffect cleanup function

Callback function is executed after the changes being pushed to the Dom
Callback executed when dependencies between renderings changed
Put your side-effect logic into the callback function, then use the dependencies argument to control when you want the side-effect to run. That's the sole purpose of useEffect.

1useEffect(function callback(){...sideeffect material},[deps])

useEffect dependencies arguments

dependencies argument in useEffect gives you the control,when the side effect logic runs or not


Absence of dependencies

The side effect materials runs every time on rendering

1import { useEffect } from 'react';
2function MyComponent() {
3  useEffect(() => {
4    // Runs after EVERY rendering
5  });  
6}

An Empty Array []:

The side effect runs after one intial rendering

1import { useEffect } from 'react';
2function MyComponent() {
3  useEffect(() => {
4    // Runs ONCE after initial rendering
5  }, []);
6}

props and states values:

the useEffect runs when the dependency values changes

1
2import { useEffect, useState } from 'react';
3function MyComponent({ prop }) {
4  const [state, setState] = useState('');
5  useEffect(() => {
6    // Runs ONCE after initial rendering
7    // and after every rendering ONLY IF prop or state changes
8  }, [prop, state]);
9}

About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share