Reputation: 5522
I'm learning react and I'm building this project that currently is very small but the Products component keep re-rendering.
As you can see I have a console.log(products);
and in the console i see it printing 4 times.
How can I avoid this re-rendering?
1. []
2. []
3. [...data here]
4. [...data here]
Network tab only shows one call to fetch the data. So that's good.
APP.JS
const app = () => {
return (
<div className="App">
<Products />
</div>
);
}
PRODUCTS.JS
const Products = props => {
const products = useSelector(state => state.products);
const dispatch = useDispatch();
const onLoadProducts = useCallback(() => dispatch(actionCreators.onLoadProducts()), [dispatch]);
useEffect(() => {
onLoadProducts();
}, [onLoadProducts]);
const flag = products.length > 0 ? 'YAY' : 'NAY';
console.log(products);
return (
<p>{flag}</p>
)
}
export default React.memo(Products);
INDEX.JS
const composeEnhancers = process.env.NODE_ENV === 'development' ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : null || compose;
const store = createStore(productsReducer, composeEnhancers(
applyMiddleware(thunk)
));
ReactDOM.render(
<React.StrictMode>
<Provider store={store}><App /></Provider>
</React.StrictMode>,
document.getElementById('root')
);
Upvotes: 0
Views: 150