Quick Start
Let's build a global counter in less than 60 seconds without creating any complex Context Providers, Actions, or Reducers.
#1. The Owner Component
First, identify the component that should "own" and initialize the state. Usually, this is the layout or a parent widget. You use createSuperState, providing a key and an initial value.
ts
Layout.tsx1import { createSuperState } from "react-use-superstate"
2import { Navbar } from "./Navbar"
3
4export function AppLayout() {
5 // 'count' is the global key, 0 is the initial value.
6 const [count, setCount] = createSuperState('count', 0)
7
8 return (
9 <div>
10 <Navbar /> {/* Does not receive count via props! */}
11
12 <main>
13 <h3>Main Controller</h3>
14 <button onClick={() => setCount(count + 1)}>
15 Increase Main: {count}
16 </button>
17 </main>
18 </div>
19 )
20}
#2. The Consumer Component
Now, somewhere deep in your Navbar, you want to read and interact with that exact same counter. Simply call useSuperState with the exact same key.
ts
Navbar.tsx1import { useSuperState } from "react-use-superstate"
2
3export function Navbar() {
4 // Uses the existing 'count' state initialized by AppLayout
5 const [count] = useSuperState('count')
6
7 return (
8 <nav>
9 <span>Cart items: {count}</span>
10 </nav>
11 )
12}
You're done!
That's literally the entire tutorial. No
<Provider> wrapping the app. No boilerplate or reducers. When the button in AppLayout is clicked, the Navbar instantly re-renders. Every state logic you know from useState applies directly here.#What's Next?
Now that you know the basics, you might want to learn how to update deep nested objects without re-rendering everything.
NextState Owners