A
A
Artem Rassadin2021-11-05 22:47:59
React
Artem Rassadin, 2021-11-05 22:47:59

Why is a React component constantly re-rendering?

Good day!
I'm learning React, at the moment I'm studying getting data from the server and outputting to the page. When I click on a picture, I need to get information about another user of the site and redirect myself to his profile. I use react, react-redux and redux.
The problem is that when I clicked on the picture, got the person's details, and redirected to their profile, my profile component keeps rerendering.

UserProfileContainer

import UserProfile from "./UserProfile";
import { connect } from "react-redux";
import { changeProfile } from "../../redux/redux-store";

const mapStateToProps = (state) => ({
    profile: state.users.profile,
})

const mapDispatchToProps = (dispatch) => ({
    customizeProfile: (profile) => {
        dispatch(changeProfile(profile))
    },
})

const UserProfileContainer = connect(mapStateToProps, mapDispatchToProps)(UserProfile)

export default UserProfileContainer;


UserProfile

// imports...

const UserProfile = (props) => {
    let computeLink = `https://social-network.samuraijs.com/api/1.0/profile/3`;

    console.log('rerender')

    axios.get(computeLink).then((response) => {
        props.customizeProfile(response.data)
    })

    return (
        <div className="main">
            {props.profile.userId}
            <ProfileInfo />
            <ProfileFormContainer />
            <Posts />
        </div>
    );
};

export default UserProfile;


ChangeProfile function (used in the UserProfileContainer component)

export const changeProfile = (profile) => ({
  type: "CHANGE_PROFILE",
  profile: profile,
})


The result of the function is processed in redux

switch (action.type) {
     case "CHANGE_PROFILE":
          return {
                ...state,
                profile: action.profile,
          };
}


I tried to solve the problem through useEffect, but it didn't work for me. Help me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-11-05
@Aetae

What is not clear here? UserProfileyou do not have memo, which means it is always updated when at least something is updated in the parent.
And then you have a cycle:
1. UserProfilerendered.
2. When rendering, it requests data and throws it into customizeProfile.
3. customizeProfilewill dispatch the update profileto redux.
4. The state profilein reduxhas changed - the update of the associated UserProfileContainer.
5. goto p.1.
In general, in no case can you execute any requests in the render, you can’t dispatch anything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question