Skip to content

Commit 85ec36f

Browse files
committed
Added currying hooks
1 parent 8291471 commit 85ec36f

File tree

48 files changed

+72
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+72
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { DependencyList, useMemo, useState } from "react";
2+
import { Equal, Expect } from "../helpers/type-utils";
3+
4+
const useCustomState = <TValue>(initial: TValue) => {
5+
const [value, set] = useState<TValue>(initial);
6+
7+
return {
8+
value,
9+
set,
10+
/**
11+
* Here, we're returning a hook from our initial hook!
12+
* This is a great way to compose behaviour.
13+
*
14+
* BUT - useComputed takes in a function which can return
15+
* any type. We want to make sure that the type of the
16+
* thing returned is inferred properly.
17+
*/
18+
useComputed: (factory: (value: any) => any, deps?: DependencyList) => {
19+
return useMemo(() => {
20+
return factory(value);
21+
}, [value, ...(deps || [])]);
22+
},
23+
};
24+
};
25+
26+
const Component = () => {
27+
const arrayOfNums = useCustomState([1, 2, 3, 4, 5, 6, 7, 8]);
28+
29+
/**
30+
* Currently, this is typed as any. How do we type it
31+
* based on the return type of the function passed to
32+
* useComputed?
33+
*/
34+
const reversedAsString = arrayOfNums.useComputed((nums) =>
35+
Array.from(nums).reverse().map(String),
36+
);
37+
38+
type test = Expect<Equal<typeof reversedAsString, string[]>>;
39+
};
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { DependencyList, useMemo, useState } from "react";
2+
import { Equal, Expect } from "../helpers/type-utils";
3+
4+
const useCustomState = <TValue>(initial: TValue) => {
5+
const [value, set] = useState<TValue>(initial);
6+
7+
return {
8+
value,
9+
set,
10+
/**
11+
* We can use a generic _inline_ here to ensure
12+
* this all still works.
13+
*/
14+
useComputed: <TComputed>(
15+
factory: (value: TValue) => TComputed,
16+
deps?: DependencyList,
17+
) => {
18+
return useMemo(() => {
19+
return factory(value);
20+
}, [value, ...(deps || [])]);
21+
},
22+
};
23+
};
24+
25+
const Component = () => {
26+
const arrayOfNums = useCustomState([1, 2, 3, 4, 5, 6, 7, 8]);
27+
28+
const reversedAsString = arrayOfNums.useComputed((nums) =>
29+
Array.from(nums).reverse().map(String),
30+
);
31+
32+
type test = Expect<Equal<typeof reversedAsString, string[]>>;
33+
};

0 commit comments

Comments
 (0)