Reputation: 4227
React hooks provides the possibility of mimicking the lifecycle method componentDidUpdate
with useEffect
without dependencies:
useEffect(() => {
// componentDidUpdate
});
How can I detect if some prop is GOING TO update with react hooks?
I need to execute some code right before some changes.
Upvotes: 1
Views: 2524
Reputation: 4988
If you are trying to mimic the behaviour of componentWillReceiveProps
you can easily put your logic inside the main body of the component:
function MyComponent(props) {
// do stuff with props (it's like componentWillReceiveProps)
return (...);
}
You don't need hooks for that.
Keep in mind that useEffect runs after your component was rendered with those props and not before.
newProps -> MyComponent is called -> DOM updated -> useEffect called
Upvotes: 0
Reputation: 281696
useEffect without a dependency will be called whenever the component re-renders. This is like a combination of componentDidMount
and componentDidUpdate
However if you wish to track a specific prop change, you can add that to the dependency array of useEffect
useEffect(() => {
// called on change of props.somename as well as initial render
}, [props.somename]);
Also check the below posts for more details on emulating lifecycle methods with useEffect as well as executing useEffect only on update
React hooks useEffect only on update?
ReactJS lifecycle method inside a function Component
P.S. You can add more than one value to the dependency array depending on your requirement
Upvotes: 2