I’m using two useEffect in single component because there are two type of dependency. In first useEffect I’m updating a state but not able to get updated state in second useEffect console.
If I’m consoling it outside of useEffect then its working fine but I need in useEffect.
Note : Click on test button then check console.log there is getting initial state value instead of updated value.
import React, { useEffect, useState } from "react";
import "./styles.css";
export default function MyComponent() {
const [editData, setEditData] = useState("initData");
const depdency1 = "depdency1";
const depdency2 = "depdency2";
useEffect(() => {
mufuction();
}, [depdency1]);
const mufuction = () => {
setEditData("Updated Data");
};
useEffect(() => {
console.log("editData", editData);
}, [depdency2]);
return <div className="App"></div>;
}
Thanks for your efforts!
3
Answers
The
dependency2
value will not change, therefore you’ll only see theconsole.log
with the value of the first render.If you want to trigger the second
useEffect
wheneditData
is altered, set the dependancy array to containseditData
:Small runnable demo:
The second
useEffect
is not running wheneditData
is updated becauseeditData
is not listed as one of its dependencies. The following code should work:Let’s redesign the layout of this component. You have a state. That state has an initial value. Let’s log the value of this state each time it is updated. Once when the component is created, and again when it is mounted.
I included both a functional and class component version.
Function component version
Class component version