Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs rendering with state or props

I would like to know difference between rendering component with state or props directly.

getInitialState:
    data: this.props.data

Following code is for render function

1.

data = this.state.data
return (<Component data={data} />)

2.

return (<Component data={this.state.data} />)

3.

return (<Component data={this.props.data} />)

First two situations are crashing when I use setState on listening reflux action. If anyone has recommendations to use other than setState or tell me the difference about those three code snippets would be very much appreciated.

like image 817
sean Avatar asked Aug 01 '26 21:08

sean


1 Answers

Putting props in state like this:

getInitialState: function () {
  return {
    someKey: this.props.someKey
  };
}

is an anti-pattern, unless you intend to modify the value of someKey later on and you use the prop as just an initial value.

So if you don't change the value of the prop passed in, you should go with number three.

The difference is that a component that doesn't have state can be considered "pure" (the same props passed in gives the same output, everytime) and those components are almost always easier to reason about. Duplicating the prop in state without mutating the state just gives you more lines of code in the component, and it might confuse someone else reading the code. It's a pure component disguised as an impure component.

like image 145
Anders Ekdahl Avatar answered Aug 03 '26 14:08

Anders Ekdahl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!