Repository navigation
refactor(mosaic): read the current time through useNow instead of during render #10098
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
3fab8d5
refactor(mosaic): read the current time through useNow instead of dur…
alexcarpenter 673b8a6
refactor(mosaic): seed useNow from a time captured by MosaicProvider
alexcarpenter 9a17a85
Merge branch 'main' into carp/mosaic-date-now-render
alexcarpenter 743602d
Merge branch 'main' into carp/mosaic-date-now-render
alexcarpenter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| --- | ||
| --- |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import { act, render as renderTree, renderHook } from '@testing-library/react'; | ||
| import type { ReactNode } from 'react'; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { MosaicProvider } from '../../mosaic-provider'; | ||
| import { MosaicNowProvider, useNow } from '../use-now'; | ||
|
|
||
| describe('useNow', () => { | ||
| beforeEach(() => { | ||
| vi.useFakeTimers(); | ||
| vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.useRealTimers(); | ||
| }); | ||
|
|
||
| const render = (updateInterval?: number) => | ||
| renderHook(({ updateInterval }) => useNow({ updateInterval }), { initialProps: { updateInterval } }); | ||
|
|
||
| const advance = (ms: number) => act(() => vi.advanceTimersByTime(ms)); | ||
|
|
||
| it('returns the time at mount', () => { | ||
| const { result } = render(60_000); | ||
| expect(result.current).toEqual(new Date('2026-01-01T00:00:00Z')); | ||
| }); | ||
|
|
||
| it('keeps the same value across re-renders between ticks', () => { | ||
| const { result, rerender } = render(60_000); | ||
| const first = result.current; | ||
|
|
||
| vi.setSystemTime(new Date('2026-01-01T00:00:30Z')); | ||
| rerender({ updateInterval: 60_000 }); | ||
|
|
||
| expect(result.current).toBe(first); | ||
| }); | ||
|
|
||
| it('advances on each interval', async () => { | ||
| const { result } = render(60_000); | ||
|
|
||
| await advance(60_000); | ||
| expect(result.current).toEqual(new Date('2026-01-01T00:01:00Z')); | ||
|
|
||
| await advance(60_000); | ||
| expect(result.current).toEqual(new Date('2026-01-01T00:02:00Z')); | ||
| }); | ||
|
|
||
| it('does not tick without an update interval', async () => { | ||
| const { result } = render(); | ||
|
|
||
| await advance(60_000); | ||
| expect(result.current).toEqual(new Date('2026-01-01T00:00:00Z')); | ||
| }); | ||
|
|
||
| it('starts ticking when the interval is set after mount', async () => { | ||
| const { result, rerender } = render(); | ||
|
|
||
| await advance(5_000); | ||
| rerender({ updateInterval: 1_000 }); | ||
| await advance(1_000); | ||
|
|
||
| expect(result.current).toEqual(new Date('2026-01-01T00:00:06Z')); | ||
| }); | ||
|
|
||
| it('stops its timer on unmount', () => { | ||
| const { unmount } = render(1_000); | ||
| unmount(); | ||
| expect(vi.getTimerCount()).toBe(0); | ||
| }); | ||
| it('starts from the provider time instead of reading the clock', () => { | ||
| const providerNow = new Date('2025-06-01T00:00:00Z'); | ||
| const wrapper = ({ children }: { children: ReactNode }) => ( | ||
| <MosaicNowProvider value={providerNow}>{children}</MosaicNowProvider> | ||
| ); | ||
|
|
||
| const { result } = renderHook(() => useNow(), { wrapper }); | ||
|
|
||
| expect(result.current).toBe(providerNow); | ||
| }); | ||
|
|
||
| it('ticks forward from the provider time', async () => { | ||
| const wrapper = ({ children }: { children: ReactNode }) => ( | ||
| <MosaicNowProvider value={new Date('2025-06-01T00:00:00Z')}>{children}</MosaicNowProvider> | ||
| ); | ||
|
|
||
| const { result } = renderHook(() => useNow({ updateInterval: 1_000 }), { wrapper }); | ||
| await advance(1_000); | ||
|
|
||
| expect(result.current).toEqual(new Date('2026-01-01T00:00:01Z')); | ||
| }); | ||
|
|
||
| it('gives components mounted later under MosaicProvider the time the provider mounted', () => { | ||
| const seen: Date[] = []; | ||
| const Consumer = () => { | ||
| seen.push(useNow()); | ||
| return null; | ||
| }; | ||
|
|
||
| const { rerender } = renderTree( | ||
| <MosaicProvider> | ||
| <Consumer /> | ||
| </MosaicProvider>, | ||
| ); | ||
| vi.setSystemTime(new Date('2026-01-01T00:05:00Z')); | ||
| rerender( | ||
| <MosaicProvider> | ||
| <Consumer /> | ||
| <Consumer /> | ||
| </MosaicProvider>, | ||
| ); | ||
|
|
||
| expect(seen.at(-1)).toEqual(new Date('2026-01-01T00:00:00Z')); | ||
| expect(new Set(seen).size).toBe(1); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { createContext, useContext, useEffect, useState } from 'react'; | ||
|
|
||
| const MosaicNowContext = createContext<Date | null>(null); | ||
|
|
||
| export const MosaicNowProvider = MosaicNowContext.Provider; | ||
|
|
||
| export function useNow({ updateInterval }: { updateInterval?: number } = {}): Date { | ||
| const providerNow = useContext(MosaicNowContext); | ||
| const [now, setNow] = useState(() => providerNow ?? new Date()); | ||
|
|
||
| useEffect(() => { | ||
| if (updateInterval === undefined) { | ||
| return; | ||
| } | ||
| const id = window.setInterval(() => setNow(new Date()), updateInterval); | ||
| return () => window.clearInterval(id); | ||
| }, [updateInterval]); | ||
|
|
||
| return now; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This wont work well with SSR, the state initializer will have different times on the server and the client, causing hydration mismatches.
I suggest we add the
new Date()to the MosaicProvider instead and put it on a context that theuseNowhook reads its initial state from. The interval still belongs here since different components might want different granularity for their reactivity (re-rendering all of these every second is heavy).When we have that shape from the start, it's a lot easier to add SSR support by passing the
new Date()result from server->client. That part would live in our framework SDKs though, they all do it a bit differently (but all already pass data server->client).An optional improvement could be to have all the intervals at the top as well so they de-duplicate. All components that should update every minute do so together instead of on their own timer, and we end up with less timers. I think this leads to quite a bit more complexity though so I'd defer that for later/if we notice it's necessary.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
haven't been considering ssr support to much since their client components, but a good reminder to keep in mind 👍🏼 673b8a6
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice!