All Articles

React Lifecycle - Using getDerivedStateFromProps with React Native and MobX

I am sure someone out there—or maybe you who are reading this post—has/have experienced infinite loop while trying to use componentDidUpdate(). Or you might have experienced that this.props and prevProps turned out to be same, so your setState inside componentDidUpdate() won’t trigger.

I personally struggled a lot with this.props and prevProps being equal, but couldn’t solve the problem. Adn the worst part was that it would work in some screens, but won’t in others.

The solution that I have found is using getDerivedStateFromProps(). While componentDidUpdate() compares this.props with prevProps or this.state with prevState, getDerivedStateFromProps() compares this.props and this.state which are written as props and state respectively.

Look at my code below

static getDerivedStateFromProps(props, state) {
        if (toJS(props.MainScreenStore.snsPostArr[0]).length !== state.prPostArr.length) {
            return {
                prPostArr: toJS(props.MainScreenStore.snsPostArr[0]),
                likedPostSet: new Set(toJS(props.MainScreenStore.snsPostArr[1]))
            }
        }
        return null;
    }

In the code above, I am trying to setState prPostArr and likedPostSet by using props.MainScreenStore.snsPostArr. I am fetching data from a server and storing the information into an observable called snsPostArr in a MobX store. The screen receives observable as a props from MainScreenStore, which handles all the requests made in MainScreen

console logs from getDerivedStateFromProps

Since both parameters are arrays, you cannot compare them by simply using ===, I am comparing the length of the two arrays. Initially both of them have the length of zero, but when the store fetches data from the server, the array from props changes, thus changing the length.

iPhone Simulator

I will write about changing the timestamp in a later post

Aug 14, 2019

AI Enthusiast and a Software Engineer