brunosduarte / github-blog

1 stars 0 forks source link

Understanding Prop Drilling and How to Solve It #4

Open brunosduarte opened 3 months ago

brunosduarte commented 3 months ago

What is Prop Drilling?

"Prop drilling" is a term used in React development to describe the process of passing data from a parent component to a child component, and so on, through multiple levels of components. This can become problematic when you need to pass data or functions to components that are several levels down the component tree, resulting in code that is difficult to manage and maintain.

Example of Prop Drilling

Let's start with a simple example to illustrate the problem of prop drilling, now with TypeScript.

import React from 'react';

interface User {
  name: string;
  age: number;
}

interface ParentComponentProps {
  user: User;
}

const App: React.FC = () => {
  const user: User = {
    name: 'Paulo',
    age: 30,
  };

  return (
    <div>
      <ParentComponent user={user} />
    </div>
  );
};

const ParentComponent: React.FC<ParentComponentProps> = ({ user }) => {
  return (
    <div>
      <ChildComponent user={user} />
    </div>
  );
};

const ChildComponent: React.FC<ParentComponentProps> = ({ user }) => {
  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
    </div>
  );
};

export default App;

In this example, the user data is passed from App to ParentComponent, and then to ChildComponent. Although this example is simple, in a larger application, there may be many levels of components, making the code difficult to maintain.

Solutions to Prop Drilling

There are several approaches to solving the prop drilling problem. Let's explore two common solutions: the Context API and the useReducer hook.

Using the Context API

The React Context API allows you to share data between components without the need to manually pass props at every level.

import React, { createContext, useContext } from 'react';

interface User {
  name: string;
  age: number;
}

const UserContext = createContext<User | undefined>(undefined);

const App: React.FC = () => {
  const user: User = {
    name: 'Paulo',
    age: 30,
  };

  return (
    <UserContext.Provider value={user}>
      <ParentComponent />
    </UserContext.Provider>
  );
};

const ParentComponent: React.FC = () => {
  return (
    <div>
      <ChildComponent />
    </div>
  );
};

const ChildComponent: React.FC = () => {
  const user = useContext(UserContext);

  if (!user) {
    return null;
  }

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
    </div>
  );
};

export default App;

With the Context API, the user is made available to any component within the UserContext.Provider without needing to be passed as a prop.

Where Find Me

Linkedin GitHub

brunosduarte
brunosduarte commented 3 months ago

Great post!

This seems to be a good post!

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