skip to Main Content

I am using useEffect to change state variables when component mounts. I am using redux for state management. The problem I am facing is that use effect is called multiple times.

React.useEffect(() => {
    
    dispatch(getSingleCoin(id))

    setName(coinDetail?.name)
    setSymbol(coinDetail?.symbol)
    setLogourl(coinDetail?.logo)
    setPrice(coinDetail?.price)
    setLaunchDate(coinDetail?.launchDate)
    setWebsiteUrl(coinDetail?.websiteUrl)
    setNetwork(coinDetail?.chain)
    setAddress(coinDetail?.address)
    setTwitterUrl(coinDetail?.twitter)
    setTelegramUrl(coinDetail?.telegram)
    setRedditUrl(coinDetail?.reddit)
    setYoutubeUrl(coinDetail?.youtube)
    setCoinDescription(coinDetail?.description)
    setMarketCap(coinDetail?.marketCap)
  }, [coinDetail,dispatch, id, approveSuccess, disapproveSuccess])

My useEffect hook that changes state variables.

export const coinDetailReducer = (state = { loading: true }, action) => {
  switch (action.type) {
    case COIN_DETAIL_REQUEST:
      return { loading: true }
    case COIN_DETAIL_SUCCESS:
      return { loading: false, coinDetail: action.payload.coin }
    case COIN_DETAIL_FAIL:
      return { loading: false, error: action.payload }
    case COIN_DETAIL_RESET:
      return {}
    default:
      return state
  }
}

My reducer that handles dispatched action.

2

Answers


  1. The useEffect runs every time one of his dependencies changes. So every time one of [coinDetail,dispatch, id, approveSuccess, disapproveSuccess] changes, it will run again.

    Maybe taking a look on the useEffect’s doc could help.

    Login or Signup to reply.
  2. Having the action dispatch and the handling its response on the same useEffect would cause infinite rendering loop. Instead have two different useEffect, one to dispatch and other to setState based on the response.

    useEffect(() => {
        dispatch(getSingleCoin(id));
      }, [dispatch, id]);
    
    useEffect(() => {
        setName(coinDetail?.name);
        setSymbol(coinDetail?.symbol);
        setLogourl(coinDetail?.logo);
        setPrice(coinDetail?.price);
        setLaunchDate(coinDetail?.launchDate);
        setWebsiteUrl(coinDetail?.websiteUrl);
        setNetwork(coinDetail?.chain);
        setAddress(coinDetail?.address);
        setTwitterUrl(coinDetail?.twitter);
        setTelegramUrl(coinDetail?.telegram);
        setRedditUrl(coinDetail?.reddit);
        setYoutubeUrl(coinDetail?.youtube);
        setCoinDescription(coinDetail?.description);
        setMarketCap(coinDetail?.marketCap);
      }, [coinDetail]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search