B
B
BMaks_N12020-12-10 00:18:58
React
BMaks_N1, 2020-12-10 00:18:58

How to prevent React.FC from rerendering on state change with hooks?

There is a Component - a functional component.
There is a repository.

I work with storage through Hooks.

How to prevent Page re-rendering on unchanged state?

For example code:

import React, {memo, useEffect} from "react";
import {useDispatch, useSelector} from "react-redux";
import {State} from "../../store/reducers/reducer";
import {setUserData} from "../../store/actions/user.actions";
import {createSelector} from "reselect";
import {UserState} from "../../store/reducers/user.reducer";
import {User} from "../../utils/types/user-types";

const selectUser = createSelector(
    (state:State) => state.user,
    (user:UserState) => {
        return user;
    }
)

const homePageFC : React.FC = () => {
    const user:User = useSelector(selectUser);
    const dispatch = useDispatch();

    useEffect(() => {
        console.log(user);

        dispatch(setUserData({id:2}));
    })

    return (
        <>
            HOMEPAGE
        </>
    )
}

const HomePage = memo(homePageFC);

export default HomePage;


How to avoid looping?
Namely, how to avoid rendering in the absence of a state change? (as with memo)
PS dragged reselect, but apparently the problem is different.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BMaks_N1, 2020-12-10
@BMaks_N1

Okay
Crap somewhere in comparison.
You need to add to the useSelector hook - shallowEqual and everything will be fine

import {shallowEqual} from "react-redux";
...
const user: User = useSelector((state: State) => state.user, shallowEqual);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question