Search code examples
reactjsuse-effectreact-context

Why dont works this Effect in React JS with context API?


Code

const GroupCoins = () => {
  const {state} = useContext(Context)
  const {data, exchangeSelected} = state
  const [coins, setCoins] = useState(data[exchangeSelected.id].coins)
  useEffect(() => {
    setCoins(data[exchangeSelected.id].coins)
  }, [exchangeSelected])
  return (
    <div className="overflow-y-auto h-9/12 rounded my-3 flex flex-col justify-items-start w-11/12 bg-gray-900 bg-opacity-10 border-gray-400 border">
      <div className="w-full text-center flex flex-row py-2 text-gray-500 font-semibold text-lg">
        <div className="w-1/6">Coin</div>
        <div className="w-4/6">Rate</div>
        <div className="w-1/6">Current Price</div>
      </div>
      {coins.map(coin => (<Coin key={coin.id} coin={coin}></Coin>))}
    </div>
  )
}

I have this effect it to detect if variable exchangeSelected is changing, im changing this variable in other component, all others components under context are refreshing but not this, i thought all components under context api be update automatically, aren't it ?


Solution

  • This is happening because you are using coins in the local state of the component. You can use the context value directly instead of using useState. Change

     const [coins, setCoins] = useState(data[exchangeSelected.id].coins)
    
    

    to

     const coins = data[exchangeSelected.id].coins;
    

    and remove useEffect altogether.

    This will automatically cause a re-render everytime your context changes .