22 lines
589 B
JavaScript
22 lines
589 B
JavaScript
|
|
import { useCallback, useEffect, useState } from 'react';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Polyfill for React 19's useOptimistic.
|
||
|
|
* Shows optimistic state immediately; reconciles when passthrough changes.
|
||
|
|
*/
|
||
|
|
export function useOptimistic(passthrough, reducer) {
|
||
|
|
const [optimistic, setOptimistic] = useState(passthrough);
|
||
|
|
|
||
|
|
// Whenever the server-confirmed state lands, sync it in.
|
||
|
|
useEffect(() => {
|
||
|
|
setOptimistic(passthrough);
|
||
|
|
}, [passthrough]);
|
||
|
|
|
||
|
|
const dispatch = useCallback(
|
||
|
|
action => setOptimistic(current => reducer(current, action)),
|
||
|
|
[reducer],
|
||
|
|
);
|
||
|
|
|
||
|
|
return [optimistic, dispatch];
|
||
|
|
}
|