Calling a mutation within React.useEffect causes infinite loop
See original GitHub issueI’m attempting to perform a mutation when a specific route is hit in my application. When using useEffect and passing through a mutation method as a dependancy, it enters an infinite loop.
const [myMutation] = useMutation(MY_MUTATION);
const Component = () => {
React.useEffect(() => {
myMutation();
}, [myMutation]);
}
This may be by design and my code an anti-pattern, if so I’d love to know an alternative way to trigger a mutation when a component is mounted for the first time.
A similar issue was fixed in graphql-hooks recently, if that helps at all.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:5
Top Results From Across the Web
How to solve the React useEffect Hook's infinite loop patterns
Solve the issue of infinite loops when using the useEffect Hook in React to more smoothly utilize the Hook for your app's side...
Read more >Infinite loop in useEffect - reactjs - Stack Overflow
Basically, the useEffect method accepts a second argument, that React will examine to determine if the effect has to be triggered again or...
Read more >How to Solve the Infinite Loop of React.useEffect()
The infinite loop is fixed by correct management of the useEffect(callback, dependencies) dependencies argument. Because you want the count to ...
Read more >A Beginner's Guide to React's useEffect Hook - CopyCat Blog
The infinite loop pitfall of useEffect() ... diverse operations we can carry out to cause a change in props or state and, consequentially, ......
Read more >Usare l'Hook Effect - React
In React class components, the render method itself shouldn't cause side effects. It would be too early — we ... Why is useEffect...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Yes, your suggestions do fix the problem but give the lint warning. But the proper way of doing this is to destructure the mutate from the mutation and provide that to the dependency array of use effect!
const {mutate} = useMutation(someFunction)useEffect(() => { mutate() }, [mutate])
Omg thank you @yaralahruthik! This solved my identical issue perfectly without requiring weird workarounds 😃