-1

So I'm trying to build a blackjack game in React. And I'm having trouble figuring out how to update the player and dealer hands when the page reloads or the player asks to take a hit. I've been experimenting with the useEffect hook but my IDE complains about the dealer and player hands being dependencies.

import React, {useEffect, useState} from 'react';
import shuffle from './components/functions/shuffle';
import deck from "./components/deck";
import CurrentPlayer from "./components/CurrentPlayer";
import dealCards from "./components/functions/dealCards";
import Cards from "./components/Cards";

function App() {
    document.body.classList.add('bg-secondary', 'text-white');
    let dealHandArr: Cards[] = [];
    let plaHandArr: Cards[] = [];
    const [dealerHand, setDealerHand] = useState<Array<Cards>>();
    const [playerHand, setPlayerHand] = useState<Array<Cards>>();
    useEffect(() => {
        shuffle(deck);
        setDealerHand(dealHandArr);
        setPlayerHand(plaHandArr);
    }, [dealHandArr, dealerHand, plaHandArr, playerHand]);
  return (
    <div className={'container'}>
        <CurrentPlayer hand={playerHand} />
    </div>
  );
}

export default App;
pdrake1988
  • 43
  • 8
  • 1
    I think you have to remove dealerHand and playerHand in dependencies. The react component will be rendered infinitely. useEffect(() => { shuffle(deck); setDealerHand(dealHandArr); setPlayerHand(plaHandArr); }, [dealHandArr, plaHandArr]); – WebEXP0528 Dec 17 '21 at 04:27
  • I guess do what the linter and @WebEXP0528 said, remove the non-dependencies `dealerHand` and `playerHand` from the dependency array if that's all your question is about. – Drew Reese Dec 17 '21 at 05:13

1 Answers1

1

You can useMemo for dealHandArr and plaHandArr so that on every rerender it won't create a new array pass that as a dependency to useEffect.

TRICK: pull array out of component that will also do the same thing(useMemo).

const dealHandArr: Cards[] = [];
const plaHandArr: Cards[] = [];
function App() {
    document.body.classList.add('bg-secondary', 'text-white');
    const [dealerHand, setDealerHand] = useState<Array<Cards>>();
    const [playerHand, setPlayerHand] = useState<Array<Cards>>();
    useEffect(() => {
        shuffle(deck);
        setDealerHand(dealHandArr);
        setPlayerHand(plaHandArr);
    }, [dealHandArr, plaHandArr]);
  return (
    <div className={'container'}>
        <CurrentPlayer hand={playerHand} />
    </div>
  );
}
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37