Skip to content

Latest commit

History

History
58 lines (43 loc) 路 1.66 KB

atom-with-default.mdx

File metadata and controls

58 lines (43 loc) 路 1.66 KB
title
atomWithDefault

Ref: #352

Usage

This is a function to create a resettable primitive atom. Its default value can be specified with a read function instead of a static initial value.

import { atomWithDefault } from 'jotai/utils'

const count1Atom = atom(1)
const count2Atom = atomWithDefault((get) => get(count1Atom) * 2)

Codesandbox

Resetting default values

You can reset the value of an atomWithDefault atom to its original default value.

import { useAtom } from 'jotai'
import { atomWithDefault, useResetAtom, RESET } from 'jotai/utils'

const count1Atom = atom(1)
const count2Atom = atomWithDefault((get) => get(count1Atom) * 2)

const Counter = () => {
  const [count1, setCount1] = useAtom(count1Atom)
  const [count2, setCount2] = useAtom(count2Atom)
  const resetCount2 = useResetAtom(count2Atom)

  return (
    <>
      <div>
        count1: {count1}, count2: {count2}
      </div>
      <button onClick={() => setCount1((c) => c + 1)}>increment count1</button>
      <button onClick={() => setCount2((c) => c + 1)}>increment count2</button>
      <button onClick={() => resetCount2()}>Reset with useResetAtom</button>
      <button onClick={() => setCount2(RESET)}>Reset with RESET const</button>
    </>
  )
}

This can be useful when an atomWithDefault atom value is overwritten using the set function, in which case the provided getter function is no longer used and any change in dependencies atoms will not trigger an update.

Resetting the value allows us to restore its original default value, discarding changes made previously via the set function.