Home > Back-end >  How to fix this error when I use useffect on react: React Hook useEffect has a missing dependency: &
How to fix this error when I use useffect on react: React Hook useEffect has a missing dependency: &

Time:03-09

I can't really figure whats wrong with my code and I get this error:

" React Hook useEffect has a missing dependency: 'props.history'. Either include it or remove the dependency array "

const mapState = ({ user }) => ({
    signInSuccess: user.signInSuccess
});

const SignIn = props => {
    const { signInSuccess } = useSelector(mapState);
    const dispatch = useDispatch();
   const [email, setEmail] = useState('');
   const [password, setPassword] = useState('');

 useEffect(() => {
    if (signInSuccess){
        resetForm()
        props.history.push('/')
    }
   }, [signInSuccess])

const resetForm = () => {
       setEmail('');
       setPassword('');
   }

CodePudding user response:

Illustrating Drew Reese's suggestion. I nixed resetForm in favor of calling your state setters directly in the useEffect hook. These functions can be excluded from the dependency array because React guarantees their consistency.

If you wanted to include the resetForm() function in your effect hook, you should construct as a memoized function with the useCallback() hook to prevent infinite re-renders.

Also, fwiw, if useEffect is routing the user to another page in your app, this component will unmount and you don't need to worry about resetting the email and password states.

const SignIn = (props) => {
  const { signInSuccess } = useSelector(mapState);
  const dispatch = useDispatch();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  useEffect(() => {
    if (signInSuccess) {
      setEmail("");
      setPassword("");
      props.history.push("/");
    }
  }, [signInSuccess, props.history]);
};
  • Related