0

I have a function component that uses hook useEffect() for dispatch action from redux. I get the action from props, it comes there from mapDispatchToProps.

const AdmRegion = props => {
  useEffect(() => {
    const { fetchRegionsListRequest } = props;
    fetchRegionsListRequest();
  }, []);
  useEffect(() => {
    console.log("render page");
  }); 

  return (
    <>

    </>
  );
};

const mapStateToProps = ({ regions }) => ({
  regionsList: regions.list
});
const mapDispatchToProps = {
  fetchRegionsListRequest
};

export default connect(mapStateToProps, mapDispatchToProps)(AdmRegion);

This action triggers the renderer three times. Is this normal behavior, or can the number of re-renders be somehow reduced? I don’t quite understand why three times. According to the action fetchRegionsListRequest, a saga is triggered which receives data from the server and puts the redux store console log screenshot

mr__scrpt
  • 31
  • 3
  • 1
    First render is initial one. After state update your component will be re-rendered one more time. Probably, you have some parent component get re-rendered at some other moment and it re-renders this one too. For instance, if you might have parent component (not direct parent, but any node above) which re-renders when request fired to show loading state or it consumes the same part of global state. – Andres Dec 05 '19 at 12:41
  • @Andres Thanks for the answer. I understood about initialization and data refresh, it will be rendered twice. I transferred this component to the highest level of the application so that it would not have any parents at all. But still, I get a third renderer. Checked the saga and request, they are executed once – mr__scrpt Dec 05 '19 at 12:56
  • Can you try moving the console.log statement to the return of the function and commenting out the second useEffect? – Konstantin Dec 05 '19 at 13:16
  • @mr_scrpt if it's possible to share you code (codesandbox or similar) we can check in more details – Andres Dec 05 '19 at 17:07

1 Answers1

0

I did a destructuring inside mapStateToProps

const mapStateToProps = ({ regions }) => ({
  regionsList: regions.list.data
});

And destructed props more simply due to this. And for some reason, the renderer now happens 2 times, as it should

const { regionsList = [] } = props;

Prior to this, props destructuring was like this, although I commented out this code and did not use it, and even removed it from the code in the first message

const {
    regionsList: { data: list = [] }
  } = props;

2 rerenders:

const mapStateToProps = ({ regions }) => ({
  regionsList: regions.list.data
});

3 rerenders:

const mapStateToProps = ({ regions }) => ({
  regionsList: regions.list
});
mr__scrpt
  • 31
  • 3