Closed
Description
Other Similar Issues: #2991
Infinite re-renders happen when trying to update local state with other than reference type of queries response in useEffect where we added queries result in dependencies array.
And also when any query response is not consistent(Meaning for first call of "posts" search gives [posts] and when no posts, return response as {message: "No data found."}), You will infinite re-renders.
Here are some examples to get better idea:
function App() {
const [fetchedReferenceTypeData, setFetchedReferenceTypeData] = useState([]);
const [localReferenceTypeState, setLocalReferenceTypeState] = useState([]);
const [primitiveState, setPrimitiveState] = useState(1);
const queries=useQueries([
{
queryKey: 'posts',
queryFn: ()=>fetchPosts()
},
{
queryKey: 'bookmarks',
queryFn: ()=>fetchBookmarks()
},
])
// ✅ - No Issues
useEffect(() => {
setPrimitiveState(2);
}, []);
// ✅
useEffect(() => {
setPrimitiveState(3);
}, [queries]);
// ✅
useEffect(() => {
setLocalReferenceTypeState(["1"]);
}, [primitiveState]);
// 🔴 - Cause Infinite re-renders since we get new array from useQueries everytime in this case.
useEffect(()=>{
// Updating the local reference type with data other than the response from queries
setLocalReferenceTypeState(["1"]);
}, [queries]);
// 🔴
useEffect(()=>{
// Updating the local reference type with data other than the response from queries
setFetchedReferenceTypeData(["1"]);
}, [queries]);
// ✅
useEffect(()=>{
// Assume here posts response type id [] of posts
setFetchedReferenceTypeData(queries.data.data);
}, [queries]);
// 🔴
useEffect(()=>{
// Can still cause infinite re-renders when there is in-consistent response from any of the queries
// Assume here posts response type is {} when there are no posts, In this we can directly add some cond in fetchPosts func itself to return consistent data type.
setFetchedReferenceTypeData(queries.data.data);
}, [queries]);
return <h1>This is the weird hook from react-query.</h1>;
}
Your minimal, reproducible example
Please look at code snippet provided
Steps to reproduce
Hope you got better Idea from above snippet.
Expected behavior
useQueries should memoize the response and should not force the consumed component to update same response when adding as dependency in useEffect.
How often does this bug happen?
Every time
Platform
OS: MacOS
Browser:Chrome
TanStack Query version
v3.39.3