Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Initiate values in render() or componentDidMount()?

I'm not quite sure where to initiate calculated values in a react component. So this is how I am doing it right now:

render () {
  const { foo } = this.props
  const { bar } = this.state

  const calculatedValue = bar ? foo * bar : foo

  return (
    <div>{calculatedValue}</div>
  )
}

Or should I initiate calculatedValue in componentDidMount()

like image 910
user3142695 Avatar asked May 21 '26 23:05

user3142695


1 Answers

I think it really depends on how much calculation you are doing. For something as simple as your example above I would usually just do that in render().

Anything above very basic functionality and I would split it out into a separate function such as getFooBarCalcValue().

This way your render method doesn't get too cluttered with things that would otherwise be elsewhere.

like image 147
Luke Glazebrook Avatar answered May 23 '26 13:05

Luke Glazebrook