I have a component which has <img src.../>
as one of the children. When I watch the network tab, the source of the image is being pulled twice on each re-render of the parent component. I have 2 questions:
- why does image loads twice, and
- how do I stop a component that contains
<img>
tag from re-rendering. Every time something happens in the parent component, the network tab shows the image being pulled twice, while I don't need it be re-pulled at all
I have tried creating a separate component which all that it has is <img>
tag. I tried it as a function and a Class and as a memoized function:
const MyImage = React.memo(props => {
console.log('render image')// logged once per render, but source pulled twice
return <img alt="" src={props.src} onLoad={props.onLoad}/>
})
and like this:
class MyImage extends React.Component {
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log(nextProps, this.props)// never logged
return nextProps.src === this.props.src;
}
render() {
console.log('render img')//logged once per render, but source pulled twice
return <img alt="" src={this.props.src} onLoad={this.props.onLoad}/>
}
}
and like this:
function MyImage(props) {
const {src, onLoad} = props;
const [source, setSource] = useState(src);
useEffect(() => {
console.log('use effect')
setSource(src);
}, []); // React Hook useEffect has a missing dependency: 'src'. But shouldn't it be empty for initial loads?
return <img alt="" src={source} onLoad={onLoad}/>
}
It seems like the onLoad
event might be causing the source to be pulled twice (if I remove it, the network tab shows only one request). But why? All that the onLoad
is doing is setting classes that are used by parent component