Skip to content
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

Feature: useHydrateAtoms #637

Merged
merged 20 commits into from
Aug 10, 2021
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions .size-snapshot.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"index.js": {
"bundled": 21267,
"minified": 10148,
"gzipped": 3367,
"bundled": 21335,
"minified": 10169,
"gzipped": 3364,
"treeshaked": {
"rollup": {
"code": 14,
Expand All @@ -14,22 +14,22 @@
}
},
"utils.js": {
"bundled": 16025,
"minified": 7685,
"gzipped": 2838,
"bundled": 16550,
"minified": 7958,
"gzipped": 2921,
"treeshaked": {
"rollup": {
"code": 28,
"import_statements": 28
},
"webpack": {
"code": 1305
"code": 1314
}
}
},
"devtools.js": {
"bundled": 19122,
"minified": 9537,
"bundled": 19190,
"minified": 9558,
"gzipped": 3288,
"treeshaked": {
"rollup": {
Expand Down
2 changes: 1 addition & 1 deletion src/core/Provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const subscribeDebugStore = (
// We keep a reference to the atoms in Provider's registeredAtoms in dev mode,
// so atoms aren't garbage collected by the WeakMap of mounted atoms
const useDebugState = (store: StoreForDevelopment) => {
const debugMutableSource = store[3]
const debugMutableSource = store[4]
const [state, atoms] = useMutableSource(
debugMutableSource,
getDebugStateAndAtoms,
Expand Down
6 changes: 4 additions & 2 deletions src/core/contexts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ const createStoreForProduction = (
atom: WritableAtom<Value, Update>,
update: Update
) => writeAtom(state, atom, update)
return [stateMutableSource, updateAtom, commitCallback] as const
const restore = (values: Iterable<readonly [Atom<unknown>, unknown]>) =>
restoreAtoms(state, values)
return [stateMutableSource, updateAtom, commitCallback, restore] as const
}

const createStoreForDevelopment = (
Expand Down Expand Up @@ -54,8 +56,8 @@ const createStoreForDevelopment = (
stateMutableSource,
updateAtom,
commitCallback,
debugMutableSource,
restore,
debugMutableSource,
Thisen marked this conversation as resolved.
Show resolved Hide resolved
] as const
}

Expand Down
2 changes: 1 addition & 1 deletion src/devtools/useAtomsSnapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type AtomsSnapshot = Map<Atom<unknown>, unknown>

export function useAtomsSnapshot(scope?: Scope): AtomsSnapshot {
const StoreContext = getStoreContext(scope)
const debugMutableSource = useContext(StoreContext)[3]
const debugMutableSource = useContext(StoreContext)[4]

if (debugMutableSource === undefined) {
throw Error('useAtomsSnapshot can only be used in dev mode.')
Expand Down
2 changes: 1 addition & 1 deletion src/devtools/useGotoAtomsSnapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function useGotoAtomsSnapshot(scope?: Scope) {
if (!isDevStore(store)) {
throw new Error('useGotoAtomsSnapshot can only be used in dev mode.')
}
const restore = store[4]
const restore = store[3]
return useCallback(
(values: Parameters<typeof restore>[0]) => {
for (const [atom] of values) {
Expand Down
1 change: 1 addition & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ export {
createJSONStorage,
} from './utils/atomWithStorage'
export { atomWithObservable } from './utils/atomWithObservable'
export { useHydrateAtoms } from './utils/useHydrateAtoms'
25 changes: 25 additions & 0 deletions src/utils/useHydrateAtoms.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useContext, useMemo } from 'react'
import { SECRET_INTERNAL_getStoreContext as getStoreContext } from 'jotai'
import type { Atom, Scope } from '../core/atom'

export function useHydrateAtoms(
values: Iterable<readonly [Atom<unknown> & { hydrated?: Symbol }, unknown]>,
scope?: Scope
) {
const StoreContext = getStoreContext(scope)
const restoreAtoms = useContext(StoreContext)[3]

useMemo(() => {
const tuplesToRestore = []
for (const tuple of values) {
const atom = tuple[0]
if (atom.hydrated !== hydratedSymbol) {
tuplesToRestore.push(tuple)
atom.hydrated = hydratedSymbol
Thisen marked this conversation as resolved.
Show resolved Hide resolved
}
}
restoreAtoms(tuplesToRestore)
}, [values, restoreAtoms])
}

const hydratedSymbol = Symbol()
216 changes: 216 additions & 0 deletions tests/utils/useHydrateAtoms.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
import { FC, useRef } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { atom, useAtom } from '../../src/index'
import { useHydrateAtoms } from '../../src/utils'
import { getTestProvider } from '../testUtils'

const Provider = getTestProvider()

it('useHydrateAtoms should only hydrate on first render', async () => {
const countAtom = atom(0)

const Counter: FC<{ initialCount: number }> = ({ initialCount }) => {
useHydrateAtoms([[countAtom, initialCount]])
const [countValue, setCount] = useAtom(countAtom)

return (
<>
<div>count: {countValue}</div>
<button onClick={() => setCount((count) => count + 1)}>dispatch</button>
</>
)
}
const { findByText, getByText, rerender } = render(
<Provider>
<Counter initialCount={42} />
</Provider>
)

await findByText('count: 42')
fireEvent.click(getByText('dispatch'))
await findByText('count: 43')

rerender(
<Provider>
<Counter initialCount={65} />
</Provider>
)
await findByText('count: 43')
})

it('useHydrateAtoms should not trigger unnessesary rerenders', async () => {
const countAtom = atom(0)

const Counter: FC<{ initialCount: number }> = ({ initialCount }) => {
useHydrateAtoms([[countAtom, initialCount]])
const [countValue, setCount] = useAtom(countAtom)
const renderCount = useRef(0)
++renderCount.current
return (
<>
<div>renders: {renderCount.current}</div>
<div>count: {countValue}</div>
<button onClick={() => setCount((count) => count + 1)}>dispatch</button>
</>
)
}

const { findByText, getByText } = render(
<Provider>
<Counter initialCount={42} />
</Provider>
)

await findByText('count: 42')
await findByText('renders: 1')
fireEvent.click(getByText('dispatch'))
await findByText('count: 43')
await findByText('renders: 2')
})

it('useHydrateAtoms should work with derived atoms', async () => {
const countAtom = atom(0)
const doubleAtom = atom((get) => get(countAtom) * 2)

const Counter: FC<{ initialCount: number }> = ({ initialCount }) => {
useHydrateAtoms([[countAtom, initialCount]])
const [countValue, setCount] = useAtom(countAtom)
const [doubleCount] = useAtom(doubleAtom)
return (
<>
<div>count: {countValue}</div>
<div>doubleCount: {doubleCount}</div>
<button onClick={() => setCount((count) => count + 1)}>dispatch</button>
</>
)
}

const { findByText, getByText } = render(
<Provider>
<Counter initialCount={42} />
</Provider>
)

await findByText('count: 42')
await findByText('doubleCount: 84')
fireEvent.click(getByText('dispatch'))
await findByText('count: 43')
await findByText('doubleCount: 86')
})

it('useHydrateAtoms can only restore an atom once', async () => {
const countAtom = atom(0)

const Counter: FC<{ initialCount: number }> = ({ initialCount }) => {
useHydrateAtoms([[countAtom, initialCount]])
const [countValue, setCount] = useAtom(countAtom)

return (
<>
<div>count: {countValue}</div>
<button onClick={() => setCount((count) => count + 1)}>dispatch</button>
</>
)
}
const Counter2: FC<{ count: number }> = ({ count }) => {
useHydrateAtoms([[countAtom, count]])
const [countValue, setCount] = useAtom(countAtom)

return (
<>
<div>count: {countValue}</div>
<button onClick={() => setCount((count) => count + 1)}>dispatch</button>
</>
)
}
const { findByText, getByText, rerender } = render(
<Provider>
<Counter initialCount={42} />
</Provider>
)

await findByText('count: 42')
fireEvent.click(getByText('dispatch'))
await findByText('count: 43')

rerender(
<Provider>
<Counter2 count={65} />
</Provider>
)

await findByText('count: 43')
fireEvent.click(getByText('dispatch'))
await findByText('count: 44')
})

it('useHydrateAtoms can only restore an atom once', async () => {
const countAtom = atom(0)

const Counter: FC<{ initialCount: number }> = ({ initialCount }) => {
useHydrateAtoms([[countAtom, initialCount]])
const [countValue, setCount] = useAtom(countAtom)

return (
<>
<div>count: {countValue}</div>
<button onClick={() => setCount((count) => count + 1)}>dispatch</button>
</>
)
}
const Counter2: FC<{ count: number }> = ({ count }) => {
useHydrateAtoms([[countAtom, count]])
const [countValue, setCount] = useAtom(countAtom)

return (
<>
<div>count: {countValue}</div>
<button onClick={() => setCount((count) => count + 1)}>dispatch</button>
</>
)
}
const { findByText, getByText, rerender } = render(
<Provider>
<Counter initialCount={42} />
</Provider>
)

await findByText('count: 42')
fireEvent.click(getByText('dispatch'))
await findByText('count: 43')

rerender(
<Provider>
<Counter2 count={65} />
</Provider>
)

await findByText('count: 43')
fireEvent.click(getByText('dispatch'))
await findByText('count: 44')
})

it('useHydrateAtoms should respect onMount', async () => {
const countAtom = atom(0)
const onMountFn = jest.fn()
countAtom.onMount = onMountFn

const Counter: FC<{ initialCount: number }> = ({ initialCount }) => {
useHydrateAtoms([[countAtom, initialCount]])
const [countValue] = useAtom(countAtom)

return (
<>
<div>count: {countValue}</div>
</>
)
}
const { findByText } = render(
<Provider>
<Counter initialCount={42} />
</Provider>
)

await findByText('count: 42')
expect(onMountFn).toBeCalledTimes(1)
})