Aliaksei
Aliaksei

Reputation: 11

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?

Upvotes: 1

Views: 1109

Answers (2)

Facundo Gallardo
Facundo Gallardo

Reputation: 384

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);

Upvotes: 0

kind user
kind user

Reputation: 41893

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(() => { ... });

Upvotes: 2

Related Questions