brunosduarte / github-blog

1 stars 0 forks source link

Creating a Reusable Component in React: Handling Unlimited Future Changes #1

Open brunosduarte opened 2 months ago

brunosduarte commented 2 months ago

When working with React, creating reusable components is essential for maintaining clean, manageable, and scalable code. One common component that frequently needs to be adaptable and flexible. In this blog post, we’ll explore how to build a reusable component that can handle various configurations and adapt to future changes without becoming overly complex.

Basic Header Component

A typical React header component might look something like this, where props are used to conditionally render elements like the logo, navigation items, search bar, and cart.

Handling Future Changes

Now, let's consider a scenario where the requirements change. The header needs to include additional elements like a favorites section, user account details, and a top banner with image and text that can be shown or hidden. If we continue using the prop-based approach, the component might look like this:

Using Compound Components

To address this issue, we can use the compound component pattern. This approach allows for more flexible and readable code by enabling the parent component to define the structure and the children to specify the content.

Here's an example of how we can refactor our header component using compound components:

Benefits of Compound Components

By using the compound component pattern, we ensure that our header component remains manageable and adaptable to future changes, providing a robust solution for complex UI requirements.

import { ThemeProvider } from "styled-components";
import { GlobalStyle } from "./styles/global";
import { defaultTheme } from "./styles/themes/default";
import { FetchProvider } from "./contexts/FetchContext";
import { RouterProvider } from "react-router-dom";
import { router } from "./pages/routes";

export function App() {
  return (
    <ThemeProvider theme={defaultTheme}>
      <GlobalStyle />
      <FetchProvider>
        <RouterProvider router={router} />
      </FetchProvider>
    </ThemeProvider>
  )
}

Where Find Me

Linkedin GitHub

brunosduarte
brunosduarte commented 2 months ago

Great post!

This seems to be an awesome post!

if (post === 'awesome') {
  return true
}
brunosduarte commented 2 months ago

Bad post!

This seems to be a very bad post!

if (post === 'very_bad') {
  return true
}