Answer the question
In order to leave comments, you need to log in
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;
// 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;
export const changeProfile = (profile) => ({
type: "CHANGE_PROFILE",
profile: profile,
})
switch (action.type) {
case "CHANGE_PROFILE":
return {
...state,
profile: action.profile,
};
}
Answer the question
In order to leave comments, you need to log in
What is not clear here? UserProfile
you 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. UserProfile
rendered.
2. When rendering, it requests data and throws it into customizeProfile
.
3. customizeProfile
will dispatch the update profile
to redux
.
4. The state profile
in redux
has 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 questionAsk a Question
731 491 924 answers to any question