Home > Mobile >  Redux probleb Error: Too many re-renders. React limits the number of renders to prevent an infinite
Redux probleb Error: Too many re-renders. React limits the number of renders to prevent an infinite

Time:10-10

if i write this its getting Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

var dispatch = useDispatch()
var phone = useSelector(store => store.phone)
 dispatch(phonePagePhone(window.location.href.split('/').splice(-1)))

but if i write thiss no errors:

 var phone = useSelector(store => store.phone)

why if i use useSelector and useDispatch in same file grtting error: Actions must be plain objects. Use custom middleware for async actions. redux

CodePudding user response:

You should be dispatching in a callback, not in the body of your component.

Like this:

const MyComponent = () => {
   const dispatch = useDispatch(); 
   const phone = useSelector(...);

   const handleSomeUserInitiatedAction = () => {
      dispatch(...);
   };
}

If you want to dispatch on first render, you could do it in a useEffect like this:


const MyComponent = () => {
   const dispatch = useDispatch(); 
   const phone = useSelector(...);

   useEffect(() => {
      dispatch(....)
   },[]);
}


  • Related