9 Stateful components
This chapter covers
- Understanding the anatomy of a stateful component
- Implementing a factory function to define components
- Implementing the first version of a component that manages its own state
Your framework works well; it manipulates the Document Object Model (DOM) so that the developer doesn’t need to, and it patches the DOM efficiently thanks to the reconciliation algorithm. But using stateless components (pure functions) forced us to move all the state to the top of the application along with the reducers. This approach isn’t ideal for several reasons:
- A component deep down in the hierarchy needs all the components above it to pass the state down to it, even when they don’t need it. As the number of levels increases, the number of components that need to pass the state down to their children gets unwieldy.
- As the application grows, the state gets bigger, and the amount of reducers increases as well. Having all these reducers together in a single place can become a bit messy.
- When a component updates the state, all the application is re-rendered, even if the component that updated the state is deep down in the hierarchy. Your reconciliation algorithm traverses the entire application’s virtual DOM (vdom) every time the state changes.