Initializing the state using props
In this section, we will see how initializing the state using props received from the parent is usually an anti-pattern. I have used the word usually because, as we will see, once we have it clear in our mind what the problems with this approach are, we might still decide to use it.
One of the best ways to learn something is by looking at the code, so we will start by creating a simple component with a + button to increment a counter.
The component is implemented using a class
:
class Counter extends React.Component
It has a constructor
where we initialize the state using the count
prop and we bind the event handler:
constructor(props) { super(props) this.state = { count: props.count, } this.handleClick = this.handleClick.bind(this) }
The implementation of the click handler is pretty straightforward: we just add 1
to the current count value and store the resulting value back into the state:
handleClick() { this.setState...