DEV Community

Kingsley onyelo
Kingsley onyelo

Posted on

HOW THE PROVIDER DESIGN PATTERN

This article aims at showing you how to implement the provider design pattern. But first, you need to know what are the various design patterns used in building a react application.

There are about six design patterns commonly used when building a react application and they are;
1.Higher order component design pattern
2.State reducer design pattern
3.Render props component design pattern
4.Provider design pattern
5.Presentational and container component design pattern
6.Hooks design pattern

The most commonly used design pattern is Render props component, In some cases, we want to make data accessible to all or most application components. Even though we can use props to pass data to components, it can be hard if almost all of your application's components need access to the props' value.

When props are passed far down the component tree, we frequently experience what is known as prop drilling. It becomes nearly impossible to refactor the props-dependent code, and it is difficult to determine where particular data originates.

The Provider Pattern can be of assistance to us in this regard! We can make data available to multiple components using the Provider Pattern. We can wrap each component in a Provider rather than passing that data through props at each layer. The Context object gives us a Provider, a higher-order component. The createContext method that React provides allows us to create a Context object.

The Provider receives a value prop, which contains the data that we want to pass down. All components that are wrapped within this provider have access to the value of the value prop.

const DataContext = React.createContext()

function App() {
  const data = { ... }

  return (
    <div>
      <DataContext.Provider value={data}>
        <SideBar />
        <Content />
      </DataContext.Provider>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Here, we have eliminated the problem of passing data down to each component using props.

Each component can get access to the data, by using the useContext hook. This hook receives the context that data has a reference with, DataContext in this case. The useContext hook lets us read and write data to the context object.

function ListItem() {
  const { data } = React.useContext(DataContext);
  return <span>{data.listItem}</span>;
}

function Text() {
  const { data } = React.useContext(DataContext);
  return <h1>{data.text}</h1>;
}

function Header() {
  const { data } = React.useContext(DataContext);
  return <div>{data.title}</div>;
}
Enter fullscreen mode Exit fullscreen mode

The Provider pattern is very useful for sharing global data. A common use case for the provider pattern is sharing a theme UI state with many components.

Thank you for reading.

Top comments (0)