So I have been thinking about this for a while, and I would like to have this settled once and for all. If possible, it would be great to explain why you think whichever way works. Does it make sense for a Modal to manage its own state or this should be managed by its Parent? In the code below, the first Modal is dumb and its fully managed by its Parent. In the second Modal, it can be managed by both its Parent and itself.
import Button from "../components/button";
const Modal = (props: { onClose: () => void }) => {
const { onClose } = props;
return (
<>
<div className="wrapper">
<p>Hello modal</p>
<button onClick={() => onClose()}>Close</button>
</div>
</>
);
};
const ModalWithState = (props: { active?: boolean; onClose: () => void }) => {
const { active, onClose } = props;
const [activeS, setActiveS] = useState(false);
useEffect(() => {
if (!active && !hasParentControl()) {
setActiveS(true);
return;
}
setActiveS(active);
}, [active]);
const hasParentControl = () => typeof active !== null;
const onCloseModal = () => {
setActiveS(false);
onClose();
};
return (
<>
{activeS && (
<div className="wrapper">
<p>Hello modal</p>
<button onClick={() => onCloseModal()}>Close</button>
<button onClick={() => setActiveS(true)}>Open</button>
</div>
)}
</>
);
};
const ParentComponent = () => {
const [activeModal, setActiveModal] = useState(false);
const openModal = () => setActiveModal(true);
return (
<>
{activeModal && <Modal onClose={() => setActiveModal(false)} />}
<ModalWithState active onClose={() => setActiveModal(false)} />
<Button onClick={() => openModal()}>Open modal</Button>
</>
);
};
There's no right or wrong answer to this. You can implement a modal in any 1 of a million ways and it depends on entirely on your use case.
In most situations I've found that modals with state tend to be more favourable for their reuability, but even that is a stretch.
In your example, you hold the active state twice, this introduces more code and it’s easier to make a mistake this way. True for any child component.
And since you can’t avoid the parent state - only the parent knows when to open the modal. I think you should skip the child state.
Having said that you can render the modal component always, and let it decide whether to render it’s content by props.
** there are ways to keep the ‘isOpen’ state only in the child, but it involves exposing a function on the child and let the parent call it. Which is kind of an antipatern for react