Component Providers in React
Sources:
Overview
About
This note is about the practice of providing state to React components using a simple wrapper that supports controlled and un-contolled props.
Component Providers are optional components that act as a higher-level API on top of component stores. They wrap components and automatically provide a store to them.
Code Example
For instance, let’s wrap ComboBox
and ComboBoxPopOver
within ComboBoxProvider
, where both components will be connected to the same store automatically:
src/components/Example.tsx
If you choose not to use component providers, you will need to manually pass the store
prop to each top-level component.
Managing State
Component Providers can also act as uncontrolled containers. In such a scenario, you can supply initial state using props.
Default State
State Setters
Component providers may also accept callbacks for state changes. These functions conventionally bear the name of the state property they modify, prefixed with the word set
. They are invoked with the new state whenever an update occurs.
These state setters serve various purposes, such as updating another state, executing side effects, or implementing features like onChange
, onValuesChange
, onToggle
, onOpenChange
, and so on.
Controlled State
You can take full control of the state by passing the exact property, without prefixes, as a prop to the provider component. In this case, the state will be considered controlled and the component will not update the state internally. It will only call the state setter. You can use this to implement a controlled component using React.useState
:
You can also receive controlled props, such as value
and onChange
, from a parent component and pass them directly to the provider component:
Passing a Store
You can use both component providers and component stores together if you need fine-grained control over the state. In this case, you can pass the store as a prop to the provider component:
Using React Context
If you’re inside a React component that’s wrapped within an Ariakit component provider, you can benefit from Ariakit context hooks to access the nearest component store in the tree:
See Also
- React Code
- React (Tool)
- JavaScript Code
- TypeScript Code
- Development Map of Content
- React Map of Content
- JavaScript Map of Content
- Hyper Text Markup Language (HTML)
- Cascading Style Sheets (CSS)
- Next.js
Appendix
Note created on 2024-04-30 and last modified on 2024-04-30.
Backlinks
(c) No Clocks, LLC | 2024