The Provider Component (When Needed)
You'll learn: When and why to use Jotai's Provider component, even though it's optional by default.
Jotai Works Without Providers
One of Jotai's biggest selling points is that atoms work globally without any provider wrapping your app. Create an atom, use it anywhere—no setup ceremony required. This is perfect for most applications.
When You Need Scoped State
However, sometimes you want independent state instances for different parts of your tree. This is where Provider comes in:
Testing Isolation
When writing tests, you don't want atoms from one test polluting another. Wrap each test's component tree in a Provider to give it a fresh, isolated state:
import { Provider } from 'jotai'
test('counter starts at zero', () => {
render(
<Provider>
<Counter />
</Provider>
)
// This Provider has its own atom state
})
Subtree Independence
Imagine a dashboard with multiple widget instances. Each widget should have its own state, not share global atoms. Wrap each widget in a Provider:
<Provider>
<Widget id="1" /> {/* Independent state */}
</Provider>
<Provider>
<Widget id="2" /> {/* Separate state */}
</Provider>
The Provider Is Like a State Boundary
Think of Provider as a fence. Without it, atoms roam free across your entire app (usually fine). With it, atoms inside that fence stay contained—perfect for isolated contexts.
Default vs Scoped
- No Provider: Atoms are global, shared across the whole app
- With Provider: Atoms get a fresh scope for that subtree
Key Takeaway: Jotai's Provider is optional but invaluable for testing isolation and creating independent state scopes within your component tree.