The state of a component is managed internally by React. Updating the state of a component directly can have unintended consequences that can be difficult to debug.
If the state is updated directly as in the example above, the component will not rerender since the state is compared shallowly. Additionally, the update may be lost if there are other state changes queued asynchronously using setState.
Another common problem is using the current state/props to update the new state.
This will potentially cause issues due to a potential race condition between other state/prop changes and this particular state update. What happens if the props and/or state change before this state update happens?
The solution for the first example is to always use the
setState function to ensure state changes are properly queued. For the second problem, React provides a different version of setState that takes a function instead of an object.
This will ensure that the state change happens with the correct version of the previous state and props.