Search code examples
reactjsreduxreact-reduxredux-toolkitstate-management

Can we make a certain function run when a Redux state value changes in Class Based React?


I'm building a project primarily using React Class Components and was wondering if there was a method that does the following:
a) Allows you to specify dependencies like the useEffect hook- specifically state objects saved in a Redux Toolkit slice
b) Runs certain code when one of the dependencies change

I'm aware that componentDidUpdate() lets you run code whenever the class' state object or props change, but I don't see a way for it to detect changes in Redux state objects


Solution

  • componentDidUpdate is the way to do that. The redux state you're interested it needs to be available as props in the component, this is done via the connect() API. Then you can read the prevProps argument of componentDidUpdate and compare the values.

    Please note that if you want to detect redux state changes caused by your own code, you're better off extending the code that dispatches the actions that change the state in the first place (active/imperative vs. passive/reactive).