Skip to content

Next.js SSR

store.ts
'use client'
import { createScopedStore } from 'stan-js'
export const { StoreProvider, useScopedStore, useStore } = createScopedStore({
user: '',
counter: 0,
})
layout.tsx
import { fetchUser, metadata } from '@/data'
import { StoreProvider } from '@/store'
import './globals.css'
const RootLayout = async ({ children }: { children: React.ReactNode }) => {
const user = await fetchUser()
return (
<html lang="en">
<body>
<StoreProvider initialValue={{ user }}>
{children}
</StoreProvider>
</body>
</html>
)
}
export default RootLayout
export { metadata }
page.tsx
'use client'
import { Counter } from '@/Counter'
import { useStore } from '@/store'
const HomePage = () => {
const { user } = useStore()
return (
<main>
<h1>
Hello {user}!
</h1>
<Counter />
</main>
)
}
export default HomePage
Counter.tsx
import { useStore } from './store'
export const Counter = () => {
const { counter, setCounter } = useStore()
return (
<section>
<button onClick={() => setCounter(prev => prev - 1)}>-</button>
<span>{counter}</span>
<button onClick={() => setCounter(prev => prev + 1)}>+</button>
</section>
)
}