Skip to content

"Mid-level" state atoms? #826

Closed Answered by dai-shi
davewasmer asked this question in Q&A
Nov 9, 2021 · 1 comments · 4 replies
Discussion options

You must be logged in to vote

Jotai is designed to cover such use cases.
Basically, you don't need to define atoms globally.

const ParentComponent = ({ foo }) => {
  const fooAtom = useMemo(() => atom(foo), [foo]))
  // ...
}

Now, the question is how to pass fooAtom to child components.

Option 1: props

const ChildComponent = ({ fooAtom }) => {
  const [foo, setFoo] = useAtom(fooAtom)
  // ...
}

const ParentComponent = ({ foo }) => {
  const fooAtom = useMemo(() => atom(foo), [foo]))
  return <ChildComponent fooAtom={fooAtom} />
}

Option 2: context

const FooAtomContext = createContext()

const ChildComponent = () => {
  const fooAtom = useContext(FooAtomContext)
  const [foo, setFoo] = useAtom(fooAtom)
  // ...
}

const 

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@davewasmer
Comment options

@davewasmer
Comment options

@dai-shi
Comment options

@davewasmer
Comment options

Answer selected by davewasmer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants