I’m trying to submit & redirect in React using useCallback
but I’m not using the hook properly. What’s the pattern for saving data and then redirecting?
const onSubmit = useCallback((data: FacilityEntity) => {
saveFacility(data);
useNavigate().navigate('/facilities', { replace: true })
}, []);
2
Answers
I believe you’ll have to move
useNavigate
outside of theuseCallback
like this:Issue
The code is breaking React’s Rules of Hooks, specifically calling it in a callback/nested function
Solution
Call all React hooks at the top level. Move the
useNavigate
hook call outside the callback function and specify all appropriate hook dependencies.Example: