简体   繁体   中英

How to prevent re-render of child component in React?

I have a problem with rerendering child component.

I have two components:

Parent:

const Parent = () => {
    const { checkAuth } = useActions();
    const { isLoading } = useSelector(state => state.authReducer);

    useEffect(() => {
        checkAuth();
    }, []);

    if (isLoading) {
        return <Loader />;
    }

    return (
        <Child />
    );
};

export default Parent;

Child:

const Child = () => {
    return (
        <div>
            Child Component
        </div>
    );
};

export default Child;

Action checkAuth() causes the isLoading change in authReducer. So, after isLoading changes, Child component re-renders.

How can I prevent re-render of Child component in this case?

How can I prevent re-render of Child component in this case?

If you are not passing any props to this Child (especially functions), wrapping child with React.memo is enough. This will provide shallow comparison which will prevent the re-render.

const Child = React.memo(() => { ... });

Have you tried having one single return in the parent component?

const Parent = () => {
    const { checkAuth } = useActions();
    const { isLoading } = useSelector(state => state.authReducer);

    useEffect(() => {
        checkAuth();
    }, []);

    return (
    <div>
      {isLoading
        ? <Loader />
        : <Child />
      }
    </div>
    );
};

export default Parent;

And of course, you should follow @kind user's input and use React memo for your Child component:

const Child = () => {
    return (
        <div>
            Child Component
        </div>
    );
};

export default React.memo(Child);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM