-
When using React Query, we may find that sometimes the query key depends on some local states of components, but the query result needs to be shared globally. For this, we usually need to use some client state management tools (react context, redux, etc.) to raise these local states to the global level so that other components can use them to compose a same query key to get the current query result. But introducing these client state management tools brings much burden to us, and that's not what we want. I'm thinking how about RQ providing a way to manage its query key by itself? My vision is as follows. // `useSharedQueryKey` is a hook for managing globally shared query keys.
import {useSharedQueryKey} from 'react-query';
const reducer = (currentQueryKey, action) => ({...currentQueryKey, ...action})
// query hook
export const useGetData = (): SharedQueryResult => {
const [sharedQueryKey, dispatch] = useSharedQueryKey(reducer, initialKey);
return [
useQuery(['XXXData', sharedQueryKey], () => fetchData(sharedQueryKey)),
dispatch
];
};
// local component1
export const LocalComponent1 = () => {
const [value, setValue] = useState('');
const [{data}, dispatch] = useGetData();
const handleChange = (e) => {
const value = e.target.value;
setValue(value);
dispatch({param1: value});
};
return (
<div>{data} <input onChange={handleChange} value={value}/> </div>
);
}
// local component2
export const LocalComponent1 = () => {
const [value, setValue] = useState('');
const [{data}, dispatch] = useGetData();
const handleChange = (e) => {
const value = e.target.value;
setValue(value);
dispatch({param2: value});
};
return (
<div>{data} <input onChange={handleChange} value={value} /> </div>
);
} RQ will provide a hook Here is a similar implementation I have done using Here is another previous discussion for reference. (#3200) If the above idea works, I can contribute to adding this. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
no, this is out of scope for react-query. There are already lots of ways to handle global client state. My recommendation is to use the url, or zustand for this.
Not sure I understand that, it's like 5 lines of code with zustand, or even less if you use an
that's it. |
Beta Was this translation helpful? Give feedback.
no, this is out of scope for react-query. There are already lots of ways to handle global client state. My recommendation is to use the url, or zustand for this.
Not sure I understand that, it's like 5 lines of code with zustand, or even less if you use an
atom
from jotai:that's it.