Great article! Just one question, what's the difference between ContextAPI and stores. Like in both i don't need to map state to props, i can access then from any component, and mutate it?
If you think of your UI components as a tree, context is state that is shared with a specific branch of the tree.
Whereas Stores are state that live outside the component tree.
Note: Context is not reactive. That means if we call setContext() multiple times, child components won't be notified of changes. So often the state passed to setContext are stores. Example:
const myStoreA = writable(...)
const myStoreB = writable(...)
setContext('myKey', {myStoreA, myStoreB })
// now when children call getContext() they will get stores that are reactive
Great article! Just one question, what's the difference between ContextAPI and stores. Like in both i don't need to map state to props, i can access then from any component, and mutate it?
If you think of your UI components as a tree, context is state that is shared with a specific branch of the tree.
Whereas Stores are state that live outside the component tree.
Note: Context is not reactive. That means if we call
setContext()
multiple times, child components won't be notified of changes. So often the state passed tosetContext
are stores. Example:Yes, very important point about context not being reactive. For that reason I almost never use it.