Skip to content

Commit

Permalink
feat: use React 19 use in useStore api
Browse files Browse the repository at this point in the history
  • Loading branch information
himself65 committed Sep 29, 2024
1 parent 9bd8ed7 commit 499d66a
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/react/Provider.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { createContext, createElement, useContext, useRef } from 'react'
import type { FunctionComponentElement, ReactNode } from 'react'
import ReactExports, {
type Context,
type FunctionComponentElement,
type ReactNode,
createContext,
createElement,
useContext,
useRef,
} from 'react'
import { createStore, getDefaultStore } from '../vanilla.ts'

type Store = ReturnType<typeof createStore>
Expand All @@ -13,8 +20,13 @@ type Options = {
store?: Store
}

// In React 19, `use` will allow calling within conditionals and loops.
// Refs: https://19.react.dev/reference/react/use#reading-context-with-use
const hook: <T>(context: Context<T>) => T =
'use' in ReactExports ? ReactExports.use : useContext

export const useStore = (options?: Options): Store => {
const store = useContext(StoreContext)
const store = hook(StoreContext)
return options?.store || store || getDefaultStore()
}

Expand Down

0 comments on commit 499d66a

Please sign in to comment.