Search code examples
reactjsreduxreact-reduxreact-hooks

React hooks Maximum update depth exceeded error


Im trying to map my redux array when the params changed. Its rendering as expected but im getting this error in console. Tried some dependencies on useeffect but cant fix it. Dont know why this happens. Thanks for helps.

Error ;

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

My code ;

    const AuthorProfile = () => {
      const params = useParams();
      const posts = useSelector(state => state.redux);
      const [postsArray, setpostsArray] = useState([]);
      const { location, history } = useReactRouter();
    
      useEffect(() => {
        if (posts.REDUX_POSTS.length) {
          setpostsArray(
            posts.REDUX_POSTS.filter(e => e.authorId === parseInt(params.id)),
          );
        }
      }, [params, posts]);
    
      const openPost = (id) => {
    history.push('/app/posts/read/' + id)
  }

  return (
    <div className="PostContainer">
      <ul className="Posts">
        {postsArray.length &&
          postsArray.map(e => (
            <li key={e.id} onClick={() => openPost(e.id)}>
              <img src={e.image ? e.image : e.authorIcon ? e.authorIcon : 
  NoAuthor} />
              <span className="PostTitle">{e.message}</span>
            </li>
          ))}
      </ul>
    </div>
  )
}

Solution

  • In this case, you don't need to maintain redundant state (postsArray), it's purely derived state from your redux data. So just compute it. This will additionally help you get rid of the infinite loop caused by the useEffect hook.

    const params = useParams();
    const posts = useSelector(state => state.redux);
    const { location, history } = useReactRouter();
        
    const postsArray = posts.REDUX_POSTS.filter(e => e.authorId === parseInt(params.id));