MitchEff
MitchEff

Reputation: 1557

React - Is it poor form to have a lot of logic in render()?

So,I've got a component called a Project, which has a child called ProjectDates.ProjectDates receives its parent's start/end dates, and calculates the percentage completion.

I'm currently doing this calculation in render() so that I don't have to do it both in componentDidUpdate and componentDidMount. Is that correct, or is there a more appropriate lifecycle hook that I should be using?

Upvotes: 0

Views: 1261

Answers (1)

Amid
Amid

Reputation: 22352

I think all your suggestions are in general wrong. Lets take them one by one:

1) componentWillMount. You can have some logic here - but it is not recommended to introduce any side dependencies here. So in really world when you usually have to interact with back end - its of little help. Must better choice - componentDidMount where you do not have such restrictions.

2) componentWillUpdate. You should be careful here - to not end up with endless loop. Calling setState here is prohibited as it might in calling componentWillUpdate again and so on. Consider using componentWillReceiveProps.

3) render. This method should not contain any other logic except the one that prepares (renders) the content of the component. Consider moving your "business" logic to componentWillReceiveProps/componentDidMount or maybe constructor if applicable.

I recommend to go through the official docs before making decisions about your architecture.

Upvotes: 3

Related Questions