Skip to content

Commit c4570eb

Browse files
authored
fix setFrameRef logic (#432)
1 parent 9f299ab commit c4570eb

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

src/hooks/useFrame.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,32 @@ export type Updater<State> = (prev: State) => State;
66
export function useFrameState<State>(
77
defaultState: State,
88
): [State, (updater: Updater<State>) => void] {
9-
const [state, setState] = useState<State>(defaultState);
9+
const stateRef = useRef(defaultState);
10+
const [, forceUpdate] = useState({});
1011

1112
const timeoutRef = useRef<number>(null);
12-
const tmpStateRef = useRef<State>(null);
13+
const updateBatchRef = useRef<Updater<State>[]>([]);
1314

1415
function setFrameState(updater: Updater<State>) {
1516
if (timeoutRef.current === null) {
16-
tmpStateRef.current = state;
17+
updateBatchRef.current = [];
1718
timeoutRef.current = raf(() => {
18-
setState(tmpStateRef.current);
19+
updateBatchRef.current.forEach(batchUpdater => {
20+
stateRef.current = batchUpdater(stateRef.current);
21+
});
1922
timeoutRef.current = null;
23+
forceUpdate({});
2024
});
2125
}
2226

23-
tmpStateRef.current = updater(tmpStateRef.current);
27+
updateBatchRef.current.push(updater);
2428
}
2529

2630
useEffect(() => {
2731
raf.cancel(timeoutRef.current);
2832
}, []);
2933

30-
return [state, setFrameState];
34+
return [stateRef.current, setFrameState];
3135
}
3236

3337
/** Lock frame, when frame pass reset the lock. */

0 commit comments

Comments
 (0)