UNPKG

1.06 kBTypeScriptView Raw
1import * as React from 'react';
2
3const MISSING_CONTEXT_ERROR = "Couldn't find a schedule context.";
4
5export const ScheduleUpdateContext = React.createContext<{
6 scheduleUpdate: (callback: () => void) => void;
7 flushUpdates: () => void;
8}>({
9 scheduleUpdate() {
10 throw new Error(MISSING_CONTEXT_ERROR);
11 },
12 flushUpdates() {
13 throw new Error(MISSING_CONTEXT_ERROR);
14 },
15});
16
17/**
18 * When screen config changes, we want to update the navigator in the same update phase.
19 * However, navigation state is in the root component and React won't let us update it from a child.
20 * This is a workaround for that, the scheduled update is stored in the ref without actually calling setState.
21 * It lets all subsequent updates access the latest state so it stays correct.
22 * Then we call setState during after the component updates.
23 */
24export default function useScheduleUpdate(callback: () => void) {
25 const { scheduleUpdate, flushUpdates } = React.useContext(
26 ScheduleUpdateContext
27 );
28
29 scheduleUpdate(callback);
30
31 React.useEffect(flushUpdates);
32}