Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
Does it make sense for a Modal to manage its own state

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>
    </>
  );
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda