Skip to content

Commit 003dae6

Browse files
committed
fix: react layout effect warning
1 parent 4fb9544 commit 003dae6

File tree

3 files changed

+10
-5
lines changed

3 files changed

+10
-5
lines changed

packages/frameworks/react/src/bindable.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { isFunction } from "@zag-js/utils"
21
import type { Bindable, BindableParams } from "@zag-js/core"
3-
import { useLayoutEffect, useRef, useState } from "react"
2+
import { isFunction } from "@zag-js/utils"
3+
import { useRef, useState } from "react"
44
import { flushSync } from "react-dom"
5+
import { useSafeLayoutEffect } from "./use-layout-effect"
56

67
const identity = (v: VoidFunction) => v()
78

@@ -23,7 +24,7 @@ export function useBindable<T>(props: () => BindableParams<T>): Bindable<T> {
2324
valueRef.current = controlled ? props().value : value
2425

2526
const prevValue = useRef(valueRef.current)
26-
useLayoutEffect(() => {
27+
useSafeLayoutEffect(() => {
2728
prevValue.current = valueRef.current
2829
}, [value, props().value])
2930

packages/frameworks/react/src/machine.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,12 @@ import type {
1414
} from "@zag-js/core"
1515
import { createScope } from "@zag-js/core"
1616
import { isFunction, isString, toArray, warn } from "@zag-js/utils"
17-
import { useLayoutEffect, useMemo, useRef } from "react"
17+
import { useMemo, useRef } from "react"
1818
import { flushSync } from "react-dom"
1919
import { useBindable } from "./bindable"
2020
import { useRefs } from "./refs"
2121
import { useTrack } from "./track"
22+
import { useSafeLayoutEffect } from "./use-layout-effect"
2223

2324
export function useMachine<T extends BaseSchema>(
2425
machine: MachineConfig<T>,
@@ -187,7 +188,7 @@ export function useMachine<T extends BaseSchema>(
187188
},
188189
}))
189190

190-
useLayoutEffect(() => {
191+
useSafeLayoutEffect(() => {
191192
state.invoke(state.initial!, "__init__")
192193
const fns = effects.current
193194
return () => {
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { useEffect, useLayoutEffect } from "react"
2+
3+
export const useSafeLayoutEffect = typeof globalThis !== "undefined" ? useLayoutEffect : useEffect

0 commit comments

Comments
 (0)