fac18 / react_game-rosa-pat-

react game
https://react-game-pat-and-rosa.netlify.com/
0 stars 2 forks source link

State in React #19

Open oliverjam opened 4 years ago

oliverjam commented 4 years ago

https://github.com/fac18/react_game-rosa-pat-/blob/e0eee8d41bb68880531ce7833887a790fd3b17b5/src/components/cards.js#L5

This is a clever solution, well done on getting it working. However it's not very Reacty, and it might have subtle bugs.

Your one piece of React state (flipped) isn't actually being used anywhere. Your real state (clickedCards) isn't managed by React—it lives outside of your component and is mutated in the click event handler.

Since React has no knowledge of clickedCards it won't re-render when it changes. The only reason this currently works is because you also call setFlipped every time you push something to clickedCards. This state update triggers a re-render of this component, which is why it picks up the mutated clickedCards. If you ever stop doing this state update (or if clickedCards is updated from another place that doesn't do it) you won't see the change reflected on the page.

A more idiomatic React way of doing this would be to store clickedCards in state and update that in the click handler.

E.g.

const Cards = props => {
  const [clickedCards, setClickedCards] = React.useState([]);
}

Relates #12