'How can we use useEffect for multiple props value changes
How can we identify props changes in functional component?. Sample code here. Can you please help me to convert this componentDidUpdate method to functional componet using useEffect or any other way.
componentDidUpdate(prevProps){
if(prevProps.props1 !== this.props.props1){
//1st Function call
}
if(prevProps.props2 !== this.props.props2){
//2nd Function call
}
}
//-----------------
useEffect(()=>{
},[props1, props2])
Solution 1:[1]
Simplest solution is to use multiple useEffect invocations, one for each prop:
useEffect(()=>{
// Something when props1 changes
},[props1])
useEffect(()=>{
// Something when props2 changes
},[props2])
If you really need a combined useEffect
(eg. if there is some shared logic), you can use useEffect
in conjunction with usePrevious
.
const prevProps1 = usePrevious(props1);
const prevProps2 = usePrevious(props2);
useEffect(() => {
// compare props1 with prevProps1 and props2 with prevProps2
}, [props1, props2]);
Note that usePrevious
is a custom hook from react-use
that needs to be installed prior use (more info here: https://github.com/streamich/react-use. TL;Dr: use npm i react-use
to install the package to use this (and other) hooks).
Solution 2:[2]
If you want to call different functions when different props change than you can multiple useEffect
for each prop change.
Try something like below:-
useEffect(()=>{
// function call when props1 change
},[props1])
useEffect(()=>{
// function call when props2 change
},[props2])
Solution 3:[3]
You can do 2 separate useEffect
for that. You don't have to put it on a single useEffect
since it's hard to identify which state did an update.
useEffect(() => {
}, [props1]);
useEffect(() => {
}, [props2]);
Solution 4:[4]
A modified approach to lorefnon's answer:
let {current: {p1, p2} = {}} = useRef()
useRef(() => {
p1 = props1 // check with if (p1!=props1)
p2 = props2 // check with if (p2!=props2)
}, [p1,p2]) // run effect when p1 or p2 change
// basically states when props1 or props2 changes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mahsan Nourani |
Solution 2 | Priyank Kachhela |
Solution 3 | Techuila |
Solution 4 |