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

Time:11-05

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?

CodePudding user response:

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

CodePudding user response:

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

I hope you can solve your issue!

  • Related