Search justacoding.blog. [Enter] to search. Click anywhere to close.

September 3rd, 2021

React Tips For Beginners – How To Structure Components (3 Tips)

When just starting out, the goal is often to just create something that “works”. This is fine, but as your skillset starts to develop – you’ll want to more carefully consider how you are composing your React application.

In React, a good understanding of component structure, or more specifically component composition, is one of the keys to a successful project.

You should think of React components as just that – components. Individual pieces that can be combined together to form your overall implementation. React really promotes this ideology, you should leverage it to your advantage!

I’ve complied a selection of what I consider to be some of the most important React tips for beginners in this regard.

Let’s get started!

1. Think in “types” of component

As your application grows, it’ll likely contain many different components, varying in size and complexity. To remain organized and maintain a sense of consistency along the way, it’s a good idea to categorize your components.

A classic approach is to break down your components into two “types”: container components and presentational components. This approach is a common one.

Container components are responsible for holding and modifying state. They can then pass this state down to the presentational components nested within.

component types
What will your component do? It should have a specific function that’s easy to define.

As the name suggests, the presentational components are responsible for display – so rendering out whatever elements are required.

Hopefully it’s clear why this could be a good idea.

You’re delegating a specific, single responsibility or role to a container component: it’ll fetch data and store it in state, for instance. That’s all it does. It’s not concerned with using this state to output something to the user. It delegates that to the relevant presentational component.

As far as React tips for beginners go – I’d say this is arguably the most important one. Really consider the actual role of each component. Don’t get this muddied, your component should do one thing and do it well! This is one of the tenets with regards to maintaining effective React component structures within your application.

Now, the presentational component receives the necessary state and handles the rest. It’s not concerned with fetching the data, or the specifics of updating state or anything like that. It just works under the assumption that it’ll receive state in a particular shape, then perform it’s task based on that.

We can also think of it like this: container components are “smart”, presentational components are “dumb”.

Of course, as you gain more experience, you can experiment with your own concepts in this regard. The container vs presentational approach is a good one to start with, however, as it simply makes a lot of sense.

2. Use small, modular building blocks

If your app is constructed from small, modular chunks – it’ll be much easier to grow and keep things neat and tidy as your project progresses.

To compliment this, another good React tip for beginners is to simply not repeat yourself. “Don’t repeat yourself” (DRY) is a core principle in programming in general, not only within the React or JavaScript ecosystem.

We can apply this principle in our React applications for cleaner, more maintainable code that’s easier to scale and grow.

Ideally, you’ll want to reach a stage where you can quickly and efficiently compose new components using existing pieces that can be easily dropped into place as required.

modular components
Small, concise building blocks each with a specific function are extremely powerful.

To achieve this, you’ll need to actively think about how to create truly generic chunks of code.

As a trivial example, your app may use a lot of modals. You obviously won’t want to construct this modal element each and every time. It’ll be much better if you have a generic <Modal/> component which handles the opening/closing of the modal and so on.

Thinking in small, generic, reusable chunks will undoubtedly save you a lot of time (and potential headaches!) later on down the line. As a beginner, simply changing (or improving) your way of thinking can be one of the most vital things you can do.

That’s why I’d consider this one an extremely important React tip!

3. Know your patterns

Often-times, there will be a previously-established pattern or mechanism to handle the problem your are facing. Either that, or utilizing one of the said mechanisms will help improve the overall quality of your implementation.

As a beginner, it’s easy to overlook or not understand the importance of design patterns in general. A top tip for React developers (or programmers of any kind) — especially beginners, would be to familiarize yourself with some of these concepts.

We’re talking specifically about how to structure React components in this article — and there are definitely some techniques you can take advantage of in this regard.

There are two specific concepts I’d like to outline in particular:

Higher-Order Components

Simply put, a higher-order component takes one component and returns another (new) component. It’ll typically enhance the initial component in some way. Be that altering the presentation, or attaching some additional logic or functionality as required.

If you’re unfamiliar, it’s worth noting that higher-order functionality is not specific to React. It’s a general programming concept. Higher-order components in React are similar conceptually to the higher-order functions that can be utilized in many programming languages.

Higher-order components in React are useful because they allow you to easily and effectively reuse code or logic as you see fit.

As a basic example, you can consider a HoC that is responsible for handling the loading state within your application:

const WithLoader = (InitialComponent) => {
   return ({ isLoading, …props }) => {
     if (!isLoading) return <InitialComponent{…props} />
     return <p>Loading…< /p>
   }
 }

As you can see, the higher-order component both receives a component (InitialComponent) and returns a component.

Based on the value of isLoading, this HoC simply returns the initial component passed in — or it returns some loading text in its place.

const InitialComponentWithLoader = WithLoader(InitialComponent)

<InitialComponentWithLoader isLoading={false} />

Here you can see how the HoC is actually used. We feed in our initial component, then use the “new” component in its place — effectively consuming the functionality contained therein.

Any component that needs to present the loading spinner (or text) can use this HoC in the same way, you don’t need to manually handle the loading element everywhere it occurs in your app!

Be sure to check out more on higher-order components in React.

Accessing children via props

The elements nested within a component can be accessed within said component by accessing the special children prop. This prop is automatically passed to each component, you don’t need to handle any of this manually.

Consider a Modal component, something which may start out looking like this:

const Modal = (props) => {
    return (
        <>
            <h1>My sample modal</h1>
            <div>{props.children}</div>
        </>
    )
}

In your application, you can do this:

<Modal>
    <p>Modal content</p>
    <p>Some more modal content!</p>
</Modal>

The paragraphs nested within Modal here are accessible within this very component itself (using props.children as demonstrated above).

Composing components in this way is effective as your children don’t need to be a specific “thing”. They can be a single node, multiple nodes, or simply undefined.

Whatever you nest within your component — this element (or elements) can be accessed in the same way via the children prop. It’s simply a useful and handy in-built mechanism for helping you out with your component composition.

The general React tip or takeaway here would be: know your patterns!

In closing

We’ve only just scratched the surface with regards to some of the principles and best practices that can be applied when thinking about how to structure your components in React.

I hope you’ve enjoyed this short article — I do intend to write more articles focussing specifically on React tips for beginners. Not only specifically around the topic of composition, but other facets of the React ecosystem.

Be sure to put these tips and principles to good use in your next project!

Stuck for ideas on what to build? Be sure to check out my article: 8 React Project Ideas For Your Portfolio as well as the other JavaScript-based articles I’ve written.

Thanks for reading!

Have any questions? Ping me over at @justacodingblog
← Back to blog