T
TanStack16mo ago
unwilling-turquoise

How to avoid useEffect for render twice?

Hi, my react query version: ^4.29.25 so I have pseudocode below my objective is, i want to insert some data use mutation to DB when the data is not exist in useEffect, but the query is running twice in development mode. I was try to prevent using useState.. but not work. how to fix that? const [isMutationExecuted, setIsMutationIsExecuted] = useState(false) useEffect(() => { if (isMutationExecuted) return const data = fetchDataFromApi() const payload; // the payload just string if (data === null) { insertData.mutate(payload) setIsMutationIsExecuted(true) } }, []) thanks
4 Replies
flat-fuchsia
flat-fuchsia16mo ago
Hello there. useEffect may run 2-3 times in development due to a StrictMode https://react.dev/reference/react/useEffect#my-effect-runs-twice-when-the-component-mounts
useEffect – React
The library for web and native user interfaces
harsh-harlequin
harsh-harlequin16mo ago
Why are you using this state and not useMutation.status ?
unwilling-turquoise
unwilling-turquoiseOP16mo ago
hi guys, thanks for your response.. the problem solved when I add option "enable" in useQuery

Did you find this page helpful?