Scope

Signature
<Scope scopeId?: string, initialize?: InitializeCallback>

valdres-react Create an isolated child store for a React subtree

Creates a scoped store that inherits state from the parent but can override values independently. Components inside the scope read and write to the scoped store.

Usage

import { Provider, Scope } from "valdres-react"

function App() {
    return (
        <Provider>
            <MainContent />
            <Scope scopeId="modal">
                <ModalContent />
            </Scope>
        </Provider>
    )
}

Props

PropTypeDescription
scopeIdstringOptional identifier. Auto-generated if omitted.
initialize(txn) => void | [Atom, value][]Optional callback to set initial values in the scope.
childrenReactNodeComponents that will use the scoped store.

Initializing state

<Scope
    scopeId="edit-form"
    initialize={txn => {
        txn.set(nameAtom, "Draft")
        txn.set(emailAtom, "")
    }}
>
    <EditForm />
</Scope>

Or with the array format:

<Scope
    scopeId="edit-form"
    initialize={() => [
        [nameAtom, "Draft"],
        [emailAtom, ""],
    ]}
>
    <EditForm />
</Scope>

Cleanup

The scope is automatically cleaned up when the component unmounts.

See also