Search code examples
javascriptreactjscomponents

In React, what is the best practice for keeping components small


Introduction

Hi, I'm a newbie in React library. I took some react classes and already implemented some mini react projects.

Now I think I know how to write 'working' react codes.

Question

I want to know how can I keep my components small and simple. Are there good practices for this?

Example

Let's say there is a parent component A and child components B, C and D. They all have some shared states and buttons.

When I implement this kind of components, I made a lot of states and handlers in component A & pass them through props to B, C, D .

I heard people are saying keeping components small is a good practice.

I want to know how to keep component small when there are a lot of child components and shared states between them. Don't we need a lot of states and handlers in component A? I don't think this is simple. It'll become messier as the number of child components increases.

I'd be appreciated if you could give some advices :)


Solution

  • Generally speaking, your example is fine. You should be trying to create ‘dumb’, reusable components where possible, and then having stateful/logic components pass data into these. Ideally, you place the state/logic as far down the chain as you can, but high enough where all components that need it can access it. This is one of the core idea's of React called lifting state up.

    take for example a <Button> component - you could pass in a route name and have logic inside the button component to navigate you to that page, but what if you later need a button that doesn't change pages? ideally you want to just pass in an onClick function that tells the button what to do.

    to use your example, component A may hold this onClick logic and pass it into the component B button. But that's fine - this way the button is still reusable elsewhere.

    As your app's grow in size, you might want to start looking into the Context API and then state management tools such as redux (or the simpler Redux toolkit) - these kind of tools make it possible to access state without having to necessarily pass it around via props. However you wouldn't need something like this for your example.

    TL;DR - example is fine, you want to keep majority of components simple/small/dumb. You will also have a number of components dealing with logic/state and that's totally fine.