@os-design/use-forwarded-state 1.0.13 → 1.0.14

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.
Files changed (2) hide show
  1. package/package.json +11 -3
  2. package/src/index.ts +57 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@os-design/use-forwarded-state",
3
- "version": "1.0.13",
3
+ "version": "1.0.14",
4
4
  "license": "UNLICENSED",
5
5
  "repository": "git@gitlab.com:os-team/libs/os-design.git",
6
6
  "main": "dist/cjs/index.js",
@@ -14,7 +14,15 @@
14
14
  "./package.json": "./package.json"
15
15
  },
16
16
  "files": [
17
- "dist"
17
+ "dist",
18
+ "src",
19
+ "!**/*.test.ts",
20
+ "!**/*.test.tsx",
21
+ "!**/__tests__",
22
+ "!**/*.stories.tsx",
23
+ "!**/*.stories.mdx",
24
+ "!**/*.example.tsx",
25
+ "!**/*.emotion.d.ts"
18
26
  ],
19
27
  "sideEffects": false,
20
28
  "scripts": {
@@ -31,5 +39,5 @@
31
39
  "peerDependencies": {
32
40
  "react": ">=18"
33
41
  },
34
- "gitHead": "0e88d3afc41e36cee61222a039ef1aa4d08115b5"
42
+ "gitHead": "3d6b264027712ef81a75379fe3fde3c76c3079af"
35
43
  }
package/src/index.ts ADDED
@@ -0,0 +1,57 @@
1
+ import {
2
+ Dispatch,
3
+ SetStateAction,
4
+ useCallback,
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ } from 'react';
10
+
11
+ interface UseForwardedStateProps<T> {
12
+ value?: T;
13
+ defaultValue?: T | (() => T);
14
+ onChange?: (value: T) => void;
15
+ }
16
+
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/ban-types
18
+ const isFunction = (value: any): value is Function =>
19
+ typeof value === 'function';
20
+
21
+ const useForwardedState = <T>({
22
+ value,
23
+ defaultValue,
24
+ onChange,
25
+ }: UseForwardedStateProps<T>): [
26
+ T | undefined,
27
+ Dispatch<SetStateAction<T | undefined>>
28
+ ] => {
29
+ const [innerValue, setInnerValue] = useState(defaultValue);
30
+ const onChangeRef = useRef(onChange);
31
+
32
+ useEffect(() => {
33
+ onChangeRef.current = onChange;
34
+ }, [onChange]);
35
+
36
+ const shouldUseInnerValue = useMemo(() => value === undefined, [value]);
37
+ const forwardedValue = useMemo(
38
+ () => (shouldUseInnerValue ? innerValue : value),
39
+ [shouldUseInnerValue, innerValue, value]
40
+ );
41
+
42
+ const setForwardedValue = useCallback<
43
+ Dispatch<SetStateAction<T | undefined>>
44
+ >(
45
+ (v) => {
46
+ const nextValue = isFunction(v) ? v(forwardedValue) : v;
47
+ if (shouldUseInnerValue) setInnerValue(nextValue);
48
+ if (onChangeRef.current && nextValue !== undefined)
49
+ onChangeRef.current(nextValue);
50
+ },
51
+ [forwardedValue, shouldUseInnerValue]
52
+ );
53
+
54
+ return [forwardedValue, setForwardedValue];
55
+ };
56
+
57
+ export default useForwardedState;