Home > Enterprise >  React - How to prevent lag during logic-based component change?
React - How to prevent lag during logic-based component change?

Time:12-19

This is my code:

export const StyledCard = (props: CardProps) => {
    const [loaded, setLoaded] = React.useState<boolean>(false);
    
    return (
        <StyledContainer>
            {<StyledImage onl oad={() => setLoaded(true)} src={props.imageURL} alt=""/>}
            {!customImageLoaded && <ComponentWhichIsNotAnImageAndCannotBeUsedAsFallbackSource />}
        </StyledContainer>
    )
}

I have a state so that a placeholder component renders when the image hasn't loaded. However, when the image finally loads, there's a short moment when BOTH (the image and the placeholder component) are rendered and this makes the container double the height before eventually removing the placeholder component.

Is there a way to prevent this short double render?

If I make the condition {loaded && <img onl oad={() => setLoaded(true)} src={props.imageURL} alt=""/>}, only the placeholder renders and the img never loads because onLoad can never trigger loaded to false.

Also note: the placeholder component isn't an image so I can't use a fallback source.

Is there anyway to optimize this and prevent the double render / lag issue?

CodePudding user response:

I assume that you can hide the image using styles. In this case the image will be loaded, and after that you will remove the hidden properties.

export const StyledCard = (props: CardProps) => {
    const [loaded, setLoaded] = React.useState<boolean>(false);

    
    return (
        <StyledContainer>
            {<StyledImage 
               style={{display: loaded ? 'block' : 'none'}} 
               onl oad={() => setLoaded(true)} src={props.imageURL} alt=""
            />}
            {!loaded && <ComponentWhichIsNotAnImageAndCannotBeUsedAsFallbackSource />}
        </StyledContainer>
    )
}
  • Related