Using React getDerivedStateFromProps with Ease

Samson Oyetola
1 min readNov 23, 2019

I once had a hard time trying to update my local State with Redux state in my component before rendering the content.

Firstly, I couldn’t do it in the component constructor because redux mapStateToProps only update the render method.

Also, I couldn’t update the local state with the redux state in the render method because I will run into “ Invariant Violation: maximum update depth exceeded “ error. Since it will be calling setState() repeatedly which can lead to an infinite loop.

I can’t use componentWillReceiveProps because it’s depreciated, So I thought of using the new static method getDerivedStateFromProps.

To update my component local state, I set a dummy variable to null which will tell me if my local state has received data from redux.

My dummy variable name is __isset.

then in the getDerivedStateFromProps static method, I can then confirm for the __isset variable,
i.e if not set, I will set redux data to the local state and turn __isset to true so I won’t be resetting data to it.

This way, I was able to initialize my local state with the Redux state easily.

Sorry, I couldn’t talk much about redux or my project.
Thanks for reading.

--

--

Samson Oyetola

Fullstack Developer and Creator of Ehex (ex) Php Framework