I’ve got a small piece of code that refuses to do as I expect and i’m dumbfounded as to why. Basically it’s a card, that will first show a the back of a card, and if it gets a value for a card, a small transition runs to reveal the card. Here’s the snippet;
const Card=({card,x,y})=>{
const [c,setCard]= useState(null);
useEffect(()=>{
if(card!==c){
setCard(card)
}
},[card,c]);
return(
<g>
<image className={`card${c?' flipped':''}`} x={x} y={y} height="180" width="120" href={`/cards/${c}.svg`}/>
<image className={`hidden-card${c?' flipped':''}`} x={x} y={y} height="180" width="120" href="/cards/back.png"/>
</g>
)
}
export default Card;
The idea is that the variable c
always starts as null so the card will always start without the .flipped
class, if the card
prop is null, the card will remain hidden and if the prop is changed to a value, it will flip the card. All of that works fine. The problem is that if the card
prop starts as a value, it immediately renders as if c
= card
so the .flipped
transition doesn’t run. Basically the images start out as if they have the .flipped
className from the first render, but it’s meant to render first as c
= null, then useEffect changes c
to the card
to run the transition. Is there something i’m missing, or am i misunderstanding useEffect?