Skip to content

useResetAtom

useResetAtom is a React hook that takes an atom and returns a function that will reset the atom back to it's deafult value.

Example 1 - Reset Count

Counter.tsx
import { atom, Provider, useResetAtom, useAtom } from "valdres-react"
 
const countAtom = atom(0)
 
const Inner = () => {
    const [count, setCount] = useAtom(countAtom)
    const increment = () => setCount(curr => curr + 1)
    const reset = useResetAtom(countAtom)
    return (
        <div className="snippet">
            <button onClick={increment}>Increment</button>
            <button onClick={reset}>Reset</button>
            <div>Current count is {count}</div>
        </div>
    )
}
 
export const Counter = () => {
    return (
        <Provider>
            <Inner />
        </Provider>
    )
}

Example 2 - Fetch data with suspense

RandomDog.tsx
import { Suspense } from "react"
import { useResetAtom, atom, useValue, Provider } from "valdres-react"
import { RenderIfClient } from "./components/RenderIfClient"
 
const randomDogImage = atom(() =>
    fetch("https://random.dog/woof.json")
        .then(res => res.json())
        .then(body => body.url),
)
 
const isVideo = (url: string) => url.match(/(?:mp4|webm)$/)
 
const RandomDogImage = () => {
    const url = useValue(randomDogImage)
    const reset = useResetAtom(randomDogImage)
    return (
        <div>
            <button onClick={reset}>Next dog please!</button>
            {!isVideo(url) && <img src={url} />}
            {isVideo(url) && <video src={url} autoPlay loop />}
        </div>
    )
}
 
export const RandomDog = () => {
    return (
        <RenderIfClient>
            <Provider>
                <Suspense fallback={<>Loading...</>}>
                    <RandomDogImage />
                </Suspense>
            </Provider>
        </RenderIfClient>
    )
}