you have to use componentDidUpdate in class components and useEffect in Function components...

componentDidUpdate like this:

    componentDidUpdate(prevProps, prevState) {
            if (prevProps.something !== this.props.something) {
                   console.log('something prop has changed.')
            }
    }

componentDidUpdate will run console.log every time the new prop is different from prevProps.

and in useEffect you just add the props to its dependency:

useEffect(()=>{
    console.log('something prop has changed.')
},[props.something]);

useEffect will call that function every time the value of that prop changes.

Answer from Ali Hamedani on Stack Overflow
Top answer
1 of 2
23

you have to use componentDidUpdate in class components and useEffect in Function components...

componentDidUpdate like this:

    componentDidUpdate(prevProps, prevState) {
            if (prevProps.something !== this.props.something) {
                   console.log('something prop has changed.')
            }
    }

componentDidUpdate will run console.log every time the new prop is different from prevProps.

and in useEffect you just add the props to its dependency:

useEffect(()=>{
    console.log('something prop has changed.')
},[props.something]);

useEffect will call that function every time the value of that prop changes.

2 of 2
1

Not sure what your question has to do with react redux but here is your code not showing the behavior you describe (there is nothing wrong with the code you posted in your question). Please provide a minimum reproducible example of your problem.

class ChildComponent extends React.Component {
  componentWillReceiveProps(nextProps) {
    console.log(this.props.myList, '==', nextProps.myList); // Outputs ['a','b','c'] == ['a','b','c']
  }
  render() {
    return (
      <pre>
        {JSON.stringify(this.props.myList, undefined, 2)}
      </pre>
    );
  }
}
const ParentCompoenent = () => {
  const [myList, setMyList] = React.useState([1, 2, 3]);
  const changeList = React.useCallback(
    () => setMyList((list) => list.concat(list.length + 1)),
    []
  );
  return (
    <div>
      <button onClick={changeList}>Change list</button>
      <ChildComponent myList={myList} />
    </div>
  );
};

ReactDOM.render(
  <ParentCompoenent />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

You should avoid using componentWillReceiveProps and maybe make the component a functional component and use the useEffect hook or use did mount, did update and possibly will unmount for class components.

🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
Reacting to Prop Changes in a React Component | Pluralsight
May 2, 2025 - Now that the component has everything ready to create the highlight side effect, all that is needed is to call the setUpdate function when the text prop has been changed.
Discussions

React Call method on *SPECIFIC* props change
I'm trying to create a react component that calls a callback function only when a prop changes from false to true. I can't have the parent control the callback directly because I need to pass child... More on stackoverflow.com
🌐 stackoverflow.com
Take an action on props change in ReactJS
As of v16.2.0, componentWillRe... based on prop changes and since you want to use both current state and previous state in render, you need to maintain, two different state variables as you are doing · However, when you update the state based on previous state, use functional setState ... More on stackoverflow.com
🌐 stackoverflow.com
How to update state when prop changes?
getDerivedStateFromProps is a static function for this purpose. Also make sure to read. Memoization is super handy https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html More on reddit.com
🌐 r/reactjs
7
4
August 1, 2018
reactjs - Call custom method on component when props update - Stack Overflow
I have a YouTubeiFrame react component that renders an empty div and then drops the YouTube iframe player in to that div using componentDidMount. All works fine. I have a cueVideo method defined on... More on stackoverflow.com
🌐 stackoverflow.com
December 18, 2015
Top answer
1 of 3
7

As of v16.2.0, componentWillReceiveProps is the right place to update state, based on prop changes and since you want to use both current state and previous state in render, you need to maintain, two different state variables as you are doing

However, when you update the state based on previous state, use functional setState method

Check this answer for more details

When to use functional setState

componentWillReceiveProps(nextProps) {
    if (nextProps.amount !== this.state.current) {
        this.setState(prevState => ({ previous: prevState.current, current: nextProps.amount }));
    }
}

According to the latest RFC to React

State derived from props/state

The purpose of this pattern is to calculate some values derived from props for use during render.

Typically componentWillReceiveProps is used for this, although if the calculation is fast enough it could just be done in render.:

From v16.3.0 onwards, you would make use of

static getDerivedStateFromProps(nextProps, prevState) {
    if (
      !prevState ||
      prevState.current !== nextProps.amount
    ) {
      return {
        previous: prevState.current,
        current: nextProps.amount
      };
    }
}
2 of 3
6

I'd like to update this answer for anyone else who comes here from Google. As of v16.8.6, componentWillReceiveProps has been marked as legacy, and is not recommended to use. Instead you should use componentDidUpdate and update your state based on the new props and previous props/previous state.

componentDidUpdate(prevProps, prevState) {
   if (this.props.someVal !== prevState.someVal) {
     this.setState({ previous: prevState.someVal, current: this.props.someVal });
   }
}

Obviously, whether you check the previous state or the previous props is up to your discretion/situation. You can implement componentDidUpdate with or without the parameters, but if you want prevState you must declare prevProps.

React Update Lifecycle

componentDidUpdate()

🌐
Today I Learned
til.hashrocket.com › posts › z1xzaupgpd-run-side-effect-when-a-prop-changes-whooks
Run side effect when a prop changes w/Hooks - Today I Learned
May 25, 2022 - In many cases it's inefficient and unnecessary to call the effect function after every render. useEffect has a second argument of an array of values. If passing in this second argument, the effect function will only run when the values change. useEffect(() => console.log('value changed!'), [props.isOpen]);
Find elsewhere
🌐
Keegan Donley
keegan.codes › blog › reacting-to-prop-changes-in-react-functional-components
Reacting to Prop Changes in React Functional Components · Keegan Donley
January 31, 2024 - This method was called after a component changed, giving you the ability to perform some series of actions based on new props, or state. If you want a refresher, you can read more in the legacy React docs, but remember, this is not the recommended approach anymore. Today, we have functional React ...
🌐
Gitbooks
developmentarc.gitbooks.io › react-indepth › content › life_cycle › update › component_will_receive_props.html
Updating and componentWillReceiveProps() · react-indepth
The data could have changed between the initial render and the two subsequent updates ... React has no way of knowing that the data didn’t change. Therefore, React needs to call componentWillReceiveProps, because the component needs to be notified of the new props (even if the new props happen ...
🌐
Reddit
reddit.com › r/reactjs › how do i handle prop change in react?
How do I handle prop change in react? : r/reactjs
April 29, 2023 - The child should only have the value as a state if it changes independently from the parent state (in which case they are two unrelated values and your problem doesn't exist) ... I would remove the state from the child component, and pass down a function from the parent that accepts and index and a new attribute. Have the parent component update the child list item, when that function is called.
🌐
Bobby Hadz
bobbyhadz.com › blog › react-update-state-when-props-change
Updating state when props change in React | bobbyhadz
Every time the props change, the logic in useEffect is rerun. ... Copied!import {useEffect, useState} from 'react'; function Child({parentCount}) { const [childCount, setChildCount] = useState(0); useEffect(() => { setChildCount(parentCount ...
🌐
ITNEXT
itnext.io › how-to-updating-state-on-prop-changes-2296a03ef08c
How to: Updating state on prop changes | by Avery Duffin | ITNEXT
December 11, 2020 - This article will show you the correct ways to assign props to state and update them on changes. So we want to assign props to state, but we want it to happen on mount and every time we get an update. The function componentWillRecieveProps does that for us but it's being phased out.
🌐
Reactgo
reactgo.com › home › how to listen for props change in vue.js
How to Listen for props change in Vue.js | Reactgo
February 5, 2023 - This below example shows you how to properly watch for the prop changes in vue.js. <template> <div id="app"> <Welcome :msg="text"/> <button @click="text='Opps'">Change TEXT</button> </div> </template> <script> import Welcome from "./components/Welcome.vue"; export default { data(){ return { text: "Hello" }; }, watch: { "text": function(val, oldVal) { console.log("new: %s, old: %s", val, oldVal); } }, components: { Welcome } }; </script>
🌐
Reddit
reddit.com › r/sveltejs › question: performing action whenever any component prop changes
r/sveltejs on Reddit: question: Performing action whenever any component prop changes
February 16, 2023 -

tl;dr:

  • how can I run a function whenever any component prop changes?

  • or, how can I force a component to get destroyed and re-created whenever the props change?

Edit: solution is keyed block: https://www.reddit.com/r/sveltejs/comments/113crbp/question_performing_action_whenever_any_component/j8psd85/


I'm creating a flashcard component that tracks the amount of time the user takes to click a button.

https://svelte.dev/repl/4507d4ca412843d693b1a15073603d81?version=3.55.1

This is easy - I can store the time when the component was created and the time when the button was clicked.

<script>
    import { createEventDispatcher } from 'svelte'
    
    export let question 
    export let answer
    
    const dispatch = createEventDispatcher()

    let startTime = new Date()
    let endTime = null
    let revealed = false
    
    function reveal() {
        revealed = true
        endTime = new Date()
    }
    
    function next() {
        dispatch('next')
    }
</script>

<h1>Q: {question}</h1>
{#if revealed}
  <h1>A: {answer}</h1>
  <p>It took you {endTime - startTime} seconds to answer the question</p>
  <button on:click={next}>Next question</button>
{:else}
  <button on:click={reveal}>Show answer</button>
{/if}

The issue is that this component is being used inside another component, which changes the question & answer props once the next button is clicked.

This forces me to manually reset the state startTime, endTime, revealed inside the function next()

function next() {
  startTime = new Date()
  endTime = null
  revealed = false
  dispatch('next')
}

Not too bad.

The issue now is that the startTime used now is the time when the component got reset, and not when the props changed.

If the container components waits a few seconds before setting the new props, then that additional time will get counted in the time to answer the flashcard.

I effectively want a way to either

  • forcefully destroy & recreate the component whenever the props change

  • or, get notified whenever the props change so that I can start the timer.

Now for single props, subscribing to the change is simple, albeit ugly & ununtuitive

export let question

$: startTime = question, new Date()

The issue now is that I want the startTime to be reset whenever any of the props change.

This seems like running through way too many hoops to accomplish a simple task - observe when the props have changed.

Is there a better way?

🌐
Reddit
reddit.com › r/sveltejs › easiest way to rerun an action when a prop changes?
Easiest way to rerun an action when a prop changes? : r/sveltejs
July 22, 2022 - If you want it to continuously receive changes you need to add the bind modifier to the prop: <MyComponent bind:someProp={foo} /> Equivalent_Ad_5386 · • 4y ago · i dont exactly see the problem if im honest. but you could do those $ stuff · it reruns the whole thing if something changes.