FormContext setError and clearError useEffect cause infinite renders
See original GitHub issueDescription
Using setError, and clearError from useFormContext in the dependency array of a useEffect hooks causes components to infinitely re-render.
I discovered this because we have the react-hooks/exhaustive-deps eslint rule enabled in our codebase, so anything external to the effect MUST be included in the dependency array.
I believe this is happening because useFormContext is providing new copies of clearError and setError on every render. I believe this could be fixed by utilizing useCallback.
Simple example (full codesandbox with usecase included in reproduction steps below)
const { setError, clearError } = useFormContext();
useEffect(() => {
if(error) {
setError(error)
} else {
clearError()
}
}, [setError, clearError, error]);
// infinitely renders
I was able to work around this for now by disabling the eslint rule for that line, but this should also be fixed for performance reasons.
I’ll take a look at making PR later today as well, but wanted to get this up first for feedback.
To Reproduce
Steps to reproduce the behavior:
- Go to CodeSandbox
- Navigate to the
DatePicker.jsfile - Notice how the form works and reports errors as usual, and renders only a few times (reported in console)
- Change the useEffect dependency array on line 58 from
WORKING_DEP_ARRAY, toINFINITE_RENDER_DEP_ARRAY. - Notice how the form infinitely renders.
Expected behavior
A component should not re-render infinitely if setError, and clearError need to be used within a useEffect dependency array. useFormContext should not return new copies of these functions every time.
Desktop
- OS: Mac OX
- Browser: Chrome
- 77.0.3865.90
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:7 (5 by maintainers)

Top Related StackOverflow Question
Boom, that works great. Thanks a ton @bluebill1049!
Updated the sandbox with the beta here and all is well: https://codesandbox.io/embed/react-hook-form-form-context-bug-8nn6w
I’ll close this issue, and I’ll keep using the beta for now and report back if I find anything weird.
Thanks again!
3.23.13-beta.1i have tested and it’s working