|
|
|
|
|
by cyberax
158 days ago
|
|
You can use Tanstack Query or Zustand for this in React. They essentially have a global state, and you can attach reactive "views" to it. They also provide ways to delay rendering until you have the data ready. Your example would look like: const id = useState(...);
const numericState = useState(0);
const q = useQuery({
queryFn: async (context) => {
const data = await fetch(..., {signal: context.signal});
const derivedState = numericState + data.something;
return `This is it ${derivedState}`;
},
queryKey: ["someState", id],
}, [id, numericState]);
...
if (q.isLoading) {
return <div>loading...</div>;
}
return <div>{q.data}</div>;
It'll handle cancellation if your state changes while the query is being evaluated, you can add deferred rendering, and so on. You can even hook it into Suspense and have "transparent" handling of in-progress queries.The downside is that mutations also need to be handled by these libraries, so it essentially becomes isomorphic to Solid's signals. |
|
Here's how Zustand gets around this, and lo-and-behold: it requires React Context :( [1] (Look at how much boilerplate is required!)
React Query at least gives you an `initialData` option [2] to populate the cache before anything is done, and it works similarly to `useState`'s initializer. The key nuance with `const [state, setState] = useState(myInitialValue)` is the initial value is set on `state` before anything renders, so you don't need to wait while the component flashes `null` or a loading state. Whatever you need it to be is there immediately, helping UIs feel faster. It's a minor detail, but it makes a big difference when you're working with more complex dependencies.
1. https://zustand.docs.pmnd.rs/guides/initialize-state-with-pr...
2. https://tanstack.com/query/v5/docs/framework/react/guides/in...
---
I guess I could abuse React Query like this...
And you'd have to use `queryClient` to mutate the state locally since we aren't dealing with server data here.But here's what I really want from the React team...