Skip to content

Commit 5337fc2

Browse files
committed
refactor(use-event-callback): simplify event$ to reduce initial rerender
1 parent 01e820a commit 5337fc2

File tree

1 file changed

+8
-20
lines changed

1 file changed

+8
-20
lines changed

src/use-event-callback.ts

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,10 @@
1-
import { useEffect, useState } from 'react'
2-
import { Observable, BehaviorSubject, Subject, noop } from 'rxjs'
1+
import { useEffect, useState, useCallback } from 'react'
2+
import { Observable, BehaviorSubject, Subject } from 'rxjs'
33

44
import { RestrictArray, VoidAsNull, Not } from './type'
55

6-
// https://stackoverflow.com/questions/55541275/typescript-check-for-the-any-type
7-
type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N
8-
9-
type IsAny<T> = IfAny<T, true, false>
10-
11-
type IsVoid<T> = IsAny<T> extends true ? false : [T] extends [void] ? true : false
12-
13-
type VoidableCallback<EventValue> = IsVoid<EventValue> extends true ? () => void : (val: EventValue) => void
14-
156
export type EventCallbackState<EventValue, State, Inputs = void> = [
16-
VoidableCallback<EventValue>,
7+
(e: EventValue) => void,
178
[State extends void ? null : State, BehaviorSubject<State | null>, BehaviorSubject<RestrictArray<Inputs> | null>]
189
]
1910
export type ReturnedState<EventValue, State, Inputs> = [
@@ -53,9 +44,11 @@ export function useEventCallback<EventValue, State = void, Inputs = void>(
5344
const inputSubject$ = new BehaviorSubject<RestrictArray<Inputs> | null>(typeof inputs === 'undefined' ? null : inputs)
5445
const stateSubject$ = new BehaviorSubject<State | null>(initialValue)
5546
const [state, setState] = useState(initialValue)
56-
const [returnedCallback, setEventCallback] = useState<VoidableCallback<EventValue>>(
57-
() => noop as VoidableCallback<EventValue>,
58-
)
47+
const [event$] = useState(new Subject<EventValue>())
48+
function eventCallback(e: EventValue) {
49+
return event$.next(e)
50+
}
51+
const returnedCallback = useCallback(eventCallback, [])
5952
const [state$] = useState(stateSubject$)
6053
const [inputs$] = useState(inputSubject$)
6154

@@ -64,12 +57,7 @@ export function useEventCallback<EventValue, State = void, Inputs = void>(
6457
}, inputs || [])
6558

6659
useEffect(() => {
67-
const event$ = new Subject<EventValue>()
68-
function eventCallback(e: EventValue) {
69-
return event$.next(e)
70-
}
7160
setState(initialValue)
72-
setEventCallback(() => eventCallback as VoidableCallback<EventValue>)
7361
let value$: Observable<State>
7462

7563
if (!inputs) {

0 commit comments

Comments
 (0)