Docs

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.tsx
import { createSuperState } from "react-use-superstate"
import { Navbar } from "./Navbar"
export function AppLayout() {
// 'count' is the global key, 0 is the initial value.
const [count, setCount] = createSuperState('count', 0)
return (
<div>
<Navbar /> {/* Does not receive count via props! */}
<main>
<h3>Main Controller</h3>
<button onClick={() => setCount(count + 1)}>
Increase Main: {count}
</button>
</main>
</div>
)
}

#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.tsx
import { useSuperState } from "react-use-superstate"
export function Navbar() {
// Uses the existing 'count' state initialized by AppLayout
const [count] = useSuperState('count')
return (
<nav>
<span>Cart items: {count}</span>
</nav>
)
}
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.