liveBook · Manning

Provider pattern

As explained in React Quickly, Second Edition

The provider pattern is a design pattern in which a provider makes a value or service available to components in a descendant hierarchy.

Suppose a menu needs the same links in several nested components. Passing `links` through components that do not use it is prop drilling. A React Context provider lets descendants read the value directly instead. section 10.1.1 section 11.4.2

Provide menu links

Create the context, wrap the relevant components, and read its value where needed: `const MenuContext = createContext([]);` `<MenuContext.Provider value={links}><Menu /></MenuContext.Provider>` Inside `Menu`, call `useContext(MenuContext)` to get the links. Import `createContext` and `useContext` from React. section 11.4.2

A consumer reads the value from the nearest provider of the same context above it. Different parts of a component tree can therefore provide different values. If no provider is found, `useContext` returns the default passed to `createContext`—an empty array in the menu example, not an error. section 10.1.3 section 10.5

As the shared value grows:

  • Put related values and functions in an object rather than providing only one value. section 11.5.2
  • Keep changing data in state, and expose functions that update it when descendants need to act on it. section 11.5.1 section 11.5.2
  • Move provider logic into a dedicated component if that makes the application clearer; a small custom hook can simplify repeated context access. section 11.5.2

For a task manager with nested components, a provider can make reducer actions easier to access. Use the pattern where descendants need shared data or actions, rather than passing them through unrelated components. section 13.3 section 10.1.1

How React Quickly, Second Edition covers it

How deep it goes
Works through context creation, provider placement, consumption, defaults, and multiple providers, then extends the pattern to stateful values.
Examples
Uses a dashboard name, menu links, button border widths, and nested task-manager actions.
What it assumes
Assumes familiarity with components and JSX while introducing createContext, Provider, and useContext through examples.
What you can do after
Build it from scratch with React Context to share a value across descendants and extend it with state and update functions.
How it connects
Connects React Context with prop drilling, useContext, custom hooks, useState, and reducers.

Also explained in

Compare how 2 books explain provider pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.