React life cycle: do’s and don’ts

UPDATE! This is how it worked before version 16.3. Keep your eyes peeled for my upcoming article about the new way to do it 🙂

 

Hi there, it’s been a while since I posted something new, and this one will be a quickie for the time being. I will update it as soon as I have more time to do so.

Lately I have been reading up on React’s life cycle and have come to some new insights. Unfortunately I do not have the time to post them all now, but I will do so soon.

For now I would just like to publish something that took me a while to find and understand – where to put stuff like ajax calls and state changes.

The following is an illustration of my findings:

 

I’ll give you a quick run-through in text as well, but that is all I have time for for now.

Initialization

This sequence only happens once, the first time that the component renders.

constructor(props)

Do: initial state
Don’t: side effects (ajax etc.)

componentWillMount()

Do: set state + optimizations
Don’t: side effects (ajax etc.)

componentDidMount()

Do: side effects (ajax etc.)
Don’t: set state

 

Props changed

When anything changes after the component has been mounted, these are the lifecycle stages that the component goes through.

componentWillReceiveProps(nextProps)

Do: set state
Don’t: side effects (ajax etc.)

shouldComponentUpdate(nextProps, nextState)

Do: set state + increase performance
Don’t: side effects (ajax etc.)

componentWillUpdate(nextProps, nextState)

Don’t: set state, side effects (ajax etc.)

componentDidUpdate(prevProps, prevState)

Do: side effects (ajax etc.)
Don’t: set state

Render

Should be pure (immutable)

Further reading

For now I will leave you with some articles that delve deeper into the subject:

Leave a Reply

Your email address will not be published. Required fields are marked *