Answer the question
In order to leave comments, you need to log in
Why is the component rendered 4 times?
There is such hoc component:
import React, {useEffect, useState} from "react";
const withData = (WrappedComponent) => {
console.log('withData')
return (props) => {
const [state, setState] = useState({
data: [],
loading: true,
error: null,
});
useEffect(() => {
props.getData()
.then(data => {
setState({
data: data,
loading: false,
error: null,
})
})
.catch(error => {
setState({
data: [],
loading: false,
error: error,
})
})
}, []);
console.log(props, state);
return state.loading
? <span>Loading</span>
: state.error
? <span>{state.error}</span>
: <WrappedComponent {...props} data={state.data}/>
};
};
export default withData;
Answer the question
In order to leave comments, you need to log in
The reason is React.StrictMode, if you remove it, then there will be 2 renders, as it should be.
Read more here
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question