Search code examples
reactjsreduxredux-thunk

Why I can't use dispatch a thunk inside useEffect?


Inside thunks.js

export const displayAlert = (text) => () => {   alert(`${text}`); }

Inside another file

const dispatch = useDispatch();

const example = () => {    
    useEffect(
        ()=>{dispatch(displayAlert('Hello'))}
        ) }

Shows me

Uncaught Error: Invalid hook call


Solution

  • Move the useDispatch hook into the component, and rename it with capital letter (to not trigger another lint warning):

    const Example = () => {
      const dispatch = useDispatch();
      useEffect(() => {
        dispatch(displayAlert("Hello"));
      });
    };
    

    See rules of hooks.