Comments (10)
That does not even allow to make sync selectors.
useStore(state => state.query(), [])
// in query
const [useStore] = create((set, get) => ({
query: () => (state.set({loading: true}), state.set({loading: false}))
}))
this raises unstoppable infinite recursion, so that even empty deps []
don't guard.
Expectation:
- Gate deps
[]
should runselectorFn
just once for the deps set, even if previous selector is not finished. - Calling (indirectly)
set
fromselectorFn
should not trigger component rerender instantly to cause recursion.
from zustand.
Not sure if calling into state inside the selector is a good idea. The selector is fired on every state change. Now the selector calling set again is pretty wild as well, shouldn’t you just fetch query and call it inside useEffect?
from zustand.
Well that’s just a footgun, I shouldn’t I guess, but that would be useful combination of useEffect, useState, store and hookleton/global state in one. Now that is not as much useful for async methods, like fetching - they oftentimes come with store.
from zustand.
i mean, not opposed, but do you have an idea how we could solve this?
from zustand.
I used to set “busy” flag to a function via https://ghub.io/icicle, but more generally that is sort of “mutex”.
Recently I’ve postponed setting to ‘useEffect’, so querying happened in different hook.
But I think some code rearrangement could help, should have a look at the source more thoroughly.
from zustand.
The selector isn’t meant to be used for effects. Supporting this would be very difficult or impossible with the current design. The selector is called when the state is updated to determine if the selected state has changed. This leads to an infinite loop if you set state in the selector: setState()
-> selector()
-> setState()
-> selector()
etc.
from zustand.
@JeremyRH i think in redux there was something that made it possible. Could setState set a flag and if it's set it will postpone the update?
let active = false
let queue = []
let raf
function setState(...args) {
if (active)
// push arguments to queue
queue.push(...args)
// cancel old frame and create new
if (raf) cancelRequestFrame(raf)
raf = requestAnimationFrame(setState)
}
active = true
// merge queued up state and empty queue
queue.forEach(...set state)
queue = []
// merge current state (if any)
... set args state
... call listeners
active = false
}
from zustand.
@drcmda You would end up with inconsistencies in state because setState
is no longer guaranteed to set state synchronously:
set({ count: get().count + 1 }) // get() wont return queued state
You can solve this by always setting state even if active
is true. The problem is the listeners are called.
Also asynchronous effects would not be blocked by this:
const useStore = create(set => ({
something: {},
async selectorWithEffect() {
const something = await waitForSomething()
set({ something })
return something
}
}))
function App() {
const promise = useStore(s => s.selectorWithEffect())
}
The callstack would be something like:
etc.
...async
(active = false)
waitForSomething
selectorWithEffect
set (active = true)
...async
(active = false)
waitForSomething
selectorWithEffect
set (active = true)
...async
waitForSomething
selectorWithEffect
useStore
from zustand.
My thoughts:
I don't think effects inside the selector is a good pattern to follow. useStore
is more like useState
or useReducer
, not useEffect
. We have to call the selector when state changes to get a new slice. Stopping set
from calling the listeners is patchwork. There could be other effects outside of set
that we have no control over. It seems like supporting this would lead to more problems than it solves. If we had the ability to only run the selector once, or when the dependencies list changes, it might be worth implementing. But I don't think this is a good idea right now.
from zustand.
Makes sense. It was just something i thought remembered about redux. But they probably came to the same conclusion: https://stackoverflow.com/questions/36730793/can-i-dispatch-an-action-in-reducer
from zustand.
Related Issues (20)
- When the set operation is executed in the 「then callback」, the 「set operation」 takes nearly a hundred times longer.
- Resetting Multiple Stores Example Doesn't Work with the Currying Required Elsewhere for Typescript Support
- 123e
- In nextjs13's app directory, how can the server components send Fetch?
- Unnecessary Renders Triggered by a Hook after Migrating to Zustand
- with immer midderware, Array type wrong HOT 2
- The reactNode is stored in the store, sometimes causing the component to lose update. HOT 1
- Is there a way to reset data when switching routes? The previous method cannot take effect#1192
- Type problem with persist HOT 3
- Reset store not working on log out
- I can't update state with new data from Tanstack Query HOT 2
- The app hanging when initializing the store with and array of objects. HOT 4
- Is there any chance to simplify types?
- How to move the router state to store?
- Website graphics rendering issues (Linux) HOT 3
- shallow not support nested object HOT 1
- Are these two methods exactly the same? HOT 1
- It’s not recommended to suspend a render based on a store value returned by useSyncExternalStore.
- RFC: How is v5-alpha? HOT 11
- should useShallow add into the documents?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from zustand.