Recently I've tried to create my own component using React Query with TinyMCE for React, but I noticed that every time I loose focus from TinyMCE editor's text area my request from React Query is sent again even though nothing has changed in my components (at least I think there is no need for rerender of the component).
Here you can see that every time I click into editor and after that outside of the editor the request is sent
I created project to simulate the problem. You can see that every time you focus and unfocus from the text area of the TinyMCE editor the request from React Query is sent. I tried to use useEffect
to know if the provided callback is called multiple times as well, but the useEffect
works as expected.
import React, { useEffect } from "react";
import {
QueryClient,
QueryClientProvider,
useQuery
} from "@tanstack/react-query";
import ReactDOM from "react-dom/client";
import { Editor } from "@tinymce/tinymce-react";
export default function MyEditor() {
return (
<div>
<Editor />
</div>
);
}
const fetchData = async () => {
console.log("Fetching data", new Date());
return await fetch("https://jsonplaceholder.typicode.com/posts/1").then((d) =>
d.json()
);
};
function App() {
useQuery(["api"], fetchData);
useEffect(() => {
console.log("This is going to be logged only once");
}, []);
return (
<form>
<h1>My editor</h1>
<MyEditor />
</form>
);
}
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById("container")).render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
These are my package versions:
{
"dependencies": {
"@tanstack/react-query": "4.3.9",
"@tinymce/tinymce-react": "4.2.0",
"react": "18.2.0",
"react-dom": "18.2.0"
}
}
I think it's because the editor renders an iframe
, you can use the refetchOnWindowFocus option to avoid refetching:
useQuery(["api"], fetchData, { refetchOnWindowFocus: false })
or perhaps using the method to ignore iframe focus described in the same doc page
It works on codesandbox