|
| 1 | +import ReactDOM from 'react-dom/client' |
| 2 | +import { |
| 3 | + PauseManager, |
| 4 | + PauseManagerProvider, |
| 5 | + QueryClient, |
| 6 | + QueryClientProvider, |
| 7 | + useQuery, |
| 8 | +} from '@tanstack/react-query' |
| 9 | +import { ReactQueryDevtools } from '@tanstack/react-query-devtools' |
| 10 | +import { memo, useRef, useSyncExternalStore } from 'react' |
| 11 | + |
| 12 | +const queryClient = new QueryClient() |
| 13 | +const pauseManager = new PauseManager(true) |
| 14 | + |
| 15 | +let counter = 1 |
| 16 | + |
| 17 | +const useCounter = () => |
| 18 | + useQuery({ |
| 19 | + queryKey: ['counter'], |
| 20 | + refetchOnMount: false, |
| 21 | + queryFn: () => counter++, |
| 22 | + }) |
| 23 | + |
| 24 | +export default function App() { |
| 25 | + return ( |
| 26 | + <QueryClientProvider client={queryClient}> |
| 27 | + <ReactQueryDevtools /> |
| 28 | + <Example /> |
| 29 | + </QueryClientProvider> |
| 30 | + ) |
| 31 | +} |
| 32 | + |
| 33 | +function Example() { |
| 34 | + const { data, refetch } = useCounter() |
| 35 | + const isPaused = useSyncExternalStore( |
| 36 | + (onStoreChange) => pauseManager.subscribe(onStoreChange), |
| 37 | + () => pauseManager.isPaused(), |
| 38 | + ) |
| 39 | + |
| 40 | + return ( |
| 41 | + <div> |
| 42 | + <p>Parent Counter: {data}</p> |
| 43 | + <div style={{ opacity: isPaused ? 0.5 : 1 }}> |
| 44 | + <PauseManagerProvider pauseManager={pauseManager}> |
| 45 | + <MemoisedChild /> |
| 46 | + </PauseManagerProvider> |
| 47 | + </div> |
| 48 | + <button onClick={() => refetch()}>Increment</button> |
| 49 | + <button onClick={() => pauseManager.setPaused(!isPaused)}> |
| 50 | + {isPaused ? 'Resume' : 'Pause'} |
| 51 | + </button> |
| 52 | + </div> |
| 53 | + ) |
| 54 | +} |
| 55 | + |
| 56 | +const MemoisedChild = memo(() => { |
| 57 | + const { data } = useCounter() |
| 58 | + const renders = useRef(0) |
| 59 | + renders.current++ |
| 60 | + |
| 61 | + return ( |
| 62 | + <> |
| 63 | + <p>Child counter: {data}</p> |
| 64 | + <p>Child renders: {renders.current}</p> |
| 65 | + </> |
| 66 | + ) |
| 67 | +}) |
| 68 | + |
| 69 | +const rootElement = document.getElementById('root') as HTMLElement |
| 70 | +ReactDOM.createRoot(rootElement).render(<App />) |
0 commit comments