1

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.