Home > Software design >  Is possible to not mount a component everytime is rendered by a father component?
Is possible to not mount a component everytime is rendered by a father component?

Time:12-19

In Father component I render Child component that is a form with states inside. When I render Father i don't want to mount Child component and reset it's states. It is possible?

I tried rendering Child component using useMemo hook, but it mounts the component everytime the hook returns it.

const Father = () => {
    const [formData, setFormData] = useState(null);

    const renderForm = useMemo(() => {
        return (
            <Child
                setDefaultFormData={(value) => setFormData(value)}
            >
            </Child>
        );
    }, [formData]);

    return (
        <>
            <div>{renderForm}</div>
        </>
    );
};

export default Father;

Any help out there? Thanks.

CodePudding user response:

You can use memo in your child, so it wont change unless it must.

Just add memo (or React.memo if not properly imported) before your child's component declaration like:

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

Or if you export it use:

export default Child;
export default memo(Child);

Note that memo and useMemo are pretty similar but different.

CodePudding user response:

I'm not quite sure why you added formData to the useMemo dependency list. You are updating formData based on the previous state, and formData is not needed in the dependency list.
Try this:

  const renderForm = useMemo(() => {
        return (
            <Child
                setDefaultFormData={(value) => setFormData(value)}
            >
            </Child>
        );
    }, []);

useMemo works as expected in this case, it only updates when some dependencies in the dependency list have been updated.

  • Related