@tamagui/use-controllable-state 1.0.1-beta.59 → 1.0.1-beta.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tamagui/use-controllable-state",
3
- "version": "1.0.1-beta.59",
3
+ "version": "1.0.1-beta.60",
4
4
  "sideEffects": false,
5
5
  "source": "src/index.ts",
6
6
  "types": "./types/index.d.ts",
@@ -8,6 +8,7 @@
8
8
  "module": "dist/esm",
9
9
  "module:jsx": "dist/jsx",
10
10
  "files": [
11
+ "src",
11
12
  "types",
12
13
  "dist"
13
14
  ],
@@ -25,7 +26,7 @@
25
26
  "react-dom": "*"
26
27
  },
27
28
  "devDependencies": {
28
- "@tamagui/build": "^1.0.1-beta.59",
29
+ "@tamagui/build": "^1.0.1-beta.60",
29
30
  "react": "*",
30
31
  "react-dom": "*"
31
32
  },
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './useControllableState'
@@ -0,0 +1,54 @@
1
+ import { useCallbackRef } from '@radix-ui/react-use-callback-ref'
2
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
3
+
4
+ // can configure to allow most-recent-wins or prop-wins
5
+ // defaults to prop-wins
6
+
7
+ export function useControllableState<T>({
8
+ prop,
9
+ defaultProp,
10
+ onChange,
11
+ strategy = 'prop-wins',
12
+ }: {
13
+ prop?: T | undefined
14
+ defaultProp: T
15
+ onChange?: ((next: T) => void) | React.Dispatch<React.SetStateAction<T>>
16
+ strategy?: 'prop-wins' | 'most-recent-wins'
17
+ }): [T, React.Dispatch<React.SetStateAction<T>>] {
18
+ const currentProp = useRef(prop)
19
+ const handleChange = useCallbackRef(onChange)
20
+ const [val, setVal] = useState(prop ?? defaultProp)
21
+ const propWins = strategy === 'prop-wins'
22
+
23
+ useEffect(() => {
24
+ currentProp.current = prop
25
+ setVal((prev) => getNextStateWithCallback(prev, prop, handleChange))
26
+ }, [prop])
27
+
28
+ return [
29
+ val,
30
+ useCallback(
31
+ (next: any) => {
32
+ if (propWins && currentProp.current !== undefined) {
33
+ return
34
+ }
35
+ setVal((prev) => {
36
+ return getNextStateWithCallback(
37
+ prev,
38
+ typeof next === 'function' ? next(prev) : next,
39
+ handleChange
40
+ )
41
+ })
42
+ },
43
+ [setVal, propWins]
44
+ ) as any,
45
+ ]
46
+ }
47
+
48
+ const getNextStateWithCallback = (prev: any, next: any, handleChange: any) => {
49
+ if (prev === next || next === undefined) {
50
+ return prev
51
+ }
52
+ handleChange(next)
53
+ return next
54
+ }