Understanding your React Component Hierarchy
Building a React project is a bit different than building a project in vanilla Javascript because of how important the component hierarchy truly is in React. The component tree affects every aspect of your project like passing props, setting state, and overall placement of functionality, so it’s impossible to avoid the hierarchy at all. Clearly planning out in advance and understanding your projects component tree will both save you time and a whole lot of headache.
Taking the extra 10 minutes to plan out the component tree ahead of time is the first step to building a good React app. There’s a ton of tools out there that’ll help you do this (I’ll link these at the bottom of the page), but I like going with the classic white board. Component trees can become messy very quickly, so start simple.
Think about the components you definitely know you’ll need and think about how each individual component functions, then start branching off. For example, let’s say we’re building an Instagram like app. We know that we’re going to have a page that’s going to display all of the images. We can call this ‘ImagePage’. We also know that each image is actually a card containing information and other components like viewing and adding comments, and liking the post. We can create a component called ‘Card’ and also create components called ‘ViewComments’, ‘AddComments’, and ‘Like’. Now that we know we’re going to have all of these components, we need to know how each component will feed into each other.
It’s important to remember that props can only be passed down from parent components to child components, they can not be passed from child to child. To review, we have the following components: ImagePage, Card, ViewComments, AddComments, and Like. The ImagePage is going to hold all of the information, so this would be the most parent element. Inside of the ImagePage, you’ll have the Card because that’ll contain the actual image, comments, and like functions. And within the Card you have ViewComments, AddComments, and Like. Let’s see where we are now.
While I won’t go into setting State, having a clear structure like this makes things significantly easier when it comes to figuring out where State for certain pieces should exist, and it also makes it easier to pass down props since we know what props are being passed where.
This was a very basic example of how your component hierarchy will look, and when you are building larger apps, the component tree will gradually evolve. It’s good to be able to both see your app as an entire app, but also see it as the bits and pieces that it is that makes up the entire app. Below I’ve linked a few tools that’ll help build out your component tree, as well as view your component tree in your console.
Links: