useEffect running before render?

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);
      <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"/>

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?

1 Like

I think you need to set a default state for your card.

outside of your Card function, above it, I think you need to call something like.

let card = c

by setting default place to start you will help the rest of the logic work, I think.

I’m pretty sure this line should act as a default state. useEffect isn’t meant to run before the first render, so the initial render should always be done with c=null. so null is essentially the default state.

1 Like

Yes, that looks right. So you have that covered. I don’t have any other ideas right now but if I think of any others I will post it. I just missed that logic on my first read through.

1 Like

Just isolated the code and it seems to work as expected, there must be a problem somewhere higher up in my code, still not really sure what could be causing this or where it is, but it’s not a problem this snippet anyway. Thanks for the help though

1 Like