Presentational & Container Components — When to Use What
One design pattern which I find very useful in building complex React and Redux projects is using “Presentational and Container Components”.
Let’s start with the basic definitions of these components:
- Deal with only the look and feel of the component.
- No access to the state (store). Any state being used is its UI state. (Rule of thumb: Most presentational components need not use its state).
- These are the components which deal with how things work.
- They access the state of the application.
- They access the actions which change the state of the application.
Advantages of Dividing Components into Container and Presentational Components:
- Separation of Concerns
- Reusability of presentational components
When I started coding in React for the first time, I started with a complex project with a single container and several presentational components. Whenever I had to make a change to any component, I had to keep passing down the props from the container down to the last presentational component which used it.
My container component also became very bulky and knew too much about every presentational component. I wasn’t getting much advantage of the separation of concerns.
I then rewired my application to allow multiple container components within my application.
Let me explain it with an example:
Consider a Tic-Tac-Toe game with 2 modes:
- play with friend
- play with computer
Once you click on the mode, you can choose to restart any game paused, or start a new game.
Each game has a timer. On click on the pause button, the timer will stop. On click on resume, the timer will start.
You can also leave the game at any time, and the game will be saved.
The division of the components would be something like this:
As you see, our Game component keeps passing props without ever using it. Let’s look at how our Container component looks like.
The Game Container component looks like this:
The Game Container knows too much — it knows about the game modes, making a move, options to save and quit the game and about the analytics. If any other new requirement comes up, it would become very difficult to maintain it.
To optimise this, let’s change some of our presentational components into container components:
Our Container Components now look like:
The individual containers are easier to understand and maintain.
If in the future, if the Tic Tac Toe Board, Timer or Quit Options become complicated we can make them each their individual containers.
You’ll find your components much easier to reuse and reason about if you divide them into two categories.medium.com