Thinking in React
This article was originally published on January 7, 2016 on The Capsule Cat Blog. For archive purposes, we moved it here!
Thinking in React Components
In React, you should think about your whole app as just a hierarchy of components.
Facebook has a great explanation of how to start breaking down your UI into a component hierarchy which you can see on their React Documentation.
Let’s look at a simple Todo List:
Let’s take this mock up and draw some boxes around our components and name them. You can start deciding what should be its own component by deciding which parts should handle themselves. Each component should only do one thing, so let’s try our hand at splitting our app up:
The first outer most box in black is the App. The teal box with “Todo List” in it is our Heading. The blue box can be our TodoList with the red boxes inside it our TodoItems. Lastly, the green box can be our TodoForm.
We can take these components that we have identified and turn them into a hierarchy:
- - Heading
- - TodoList
- — TodoItem
- - TodoForm
Thinking About State
React is all about one-way data flow. Our data should only flow down the component hierarchy. But which part of the app should own that state? The least common ancestor component that uses the state (or any component higher up on the hierarchy than that one) is usually the most likely answer.
For example, the tasks in our Todo List are only used in the TodoListcomponent, so the TodoList or the App component should own that data and pass it along to the child components.
All in One File
When you write your code as components, all of these problems disappear.
The hierarchical approach and one way data flow, with a heavy reliance on internalized state make thinking about your views easy — once you get the hang of breaking up your views into components.
Thanks for reading! If you liked this article, feel free to follow us on Twitter.