Skip to content

Commit

Permalink
Use native useId and useSyncExternalStore hooks (#3092)
Browse files Browse the repository at this point in the history
* use native `useSyncExternalStore` hook from React 18

* use native `useId` hook from React 18

* update changelog
  • Loading branch information
RobinMalfait authored Apr 11, 2024
1 parent 8652f80 commit ed98bad
Show file tree
Hide file tree
Showing 6 changed files with 4 additions and 239 deletions.
1 change: 1 addition & 0 deletions packages/@headlessui-react/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Attempt form submission when pressing `Enter` on the `<Listbox.Button />` component ([#2972](https://github.com/tailwindlabs/headlessui/pull/2972))
- Make the `Combobox` component `nullable` by default ([#3064](https://github.com/tailwindlabs/headlessui/pull/3064))
- Deprecate the `entered` prop on the `Transition` component ([#3089](https://github.com/tailwindlabs/headlessui/pull/3089))
- Use native `useId` and `useSyncExternalStore` hooks ([#3092](https://github.com/tailwindlabs/headlessui/pull/3092))

### Added

Expand Down
26 changes: 2 additions & 24 deletions packages/@headlessui-react/src/hooks/use-id.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,2 @@
import React from 'react'
import { env } from '../utils/env'
import { useIsoMorphicEffect } from './use-iso-morphic-effect'
import { useServerHandoffComplete } from './use-server-handoff-complete'

// We used a "simple" approach first which worked for SSR and rehydration on the client. However we
// didn't take care of the Suspense case. To fix this we used the approach the @reach-ui/auto-id
// uses.
//
// Credits: https://github.com/reach/reach-ui/blob/develop/packages/auto-id/src/index.tsx

export let useId =
// Prefer React's `useId` if it's available.
React.useId ??
function useId() {
let ready = useServerHandoffComplete()
let [id, setId] = React.useState(ready ? () => env.nextId() : null)

useIsoMorphicEffect(() => {
if (id === null) setId(env.nextId())
}, [id])

return id != null ? '' + id : undefined
}
// Re-exporting the useId hook such that we can easily mock this hook in tests.
export { useId } from 'react'
2 changes: 1 addition & 1 deletion packages/@headlessui-react/src/hooks/use-store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useSyncExternalStore } from '../use-sync-external-store-shim/index'
import { useSyncExternalStore } from 'react'
import type { Store } from '../utils/store'

export function useStore<T>(store: Store<T, any>) {
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

0 comments on commit ed98bad

Please sign in to comment.