Lineesh Mb
Lineesh Mb

Reputation: 77

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])

Upvotes: 0

Views: 2682

Answers (4)

lorefnon
lorefnon

Reputation: 13115

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).

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

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.

Upvotes: 0

Techuila
Techuila

Reputation: 1287

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]);

Upvotes: 0

Priyank Kachhela
Priyank Kachhela

Reputation: 2635

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])

Upvotes: 0

Related Questions