V
V
Vlad Osadchyi2020-04-20 00:09:05
React
Vlad Osadchyi, 2020-04-20 00:09:05

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;


Console:
5e9cbd4b1691c490814899.png

Judging by the console, the component is rendered 4 times... Why is that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vlad Osadchyi, 2020-04-20
@VladOsadchyi

The reason is React.StrictMode, if you remove it, then there will be 2 renders, as it should be.
Read more here

V
Vladimir, 2020-04-20
@HistoryART

If the component was rendered 4 times, there would be 4 console.log('withData'), otherwise deal with the function itself that you return.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question