Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
Can't update parent component state with React UseState

im facing this weird behavior when trying to update the parent component with an set function to the child with props this hook is to open and close the modal to edit an element

//PARENT FILE

//hook
  const [isEditModalOpen, setEditModalOpen] = useState(false) 

//more code...

//modal
 {isEditModalOpen && <EditExcerciseModal setEditModalOpen={setEditModalOpen} isEditModalOpen={isEditModalOpen} />}


and this is the child code

//CHILD FILE

export const EditExcerciseModal = ({setEditModalOpen, excerciseInfo,fetchExcercisesFromRoutine}) 
//more code etc etc

   <div className="addExcerciseModalContainer">
                <span onClick={() =>{ setEditModalOpen(false) }} className="xModal">X</span>

i checked and the onClick is working. if i change the parent state manually the Modal works fine and closes.

the weird case when it its working is when instead of calling the set function i create a function with a setTimeout without time like this:

  function closeModal(){

        setTimeout(() => {  setEditModalOpen(false)}, 0);
        
    }

any ideas? thanks for the help

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to create a separation of concern. A Modal consists of three parts

  • The Modal of its Self.
  • The Content of the Modal.
  • And the container of the two.

You should be using the useState() hook and calling setEditModalOpen in the same containing component.

You need to make sure that you're declaring and setting state inside the same component.

// children would be the content of the modal
const Modal = ({ children, selector, open, setOpen }) => {
  // we need the useEffect hook so that when we change open to false
  // the modal component will re-render and the portal will not be created
  useEffect(() => {
    setOpen(false);
    //provide useEffect hook with clean up.
    return () => setOpen(true);
  }, [selector]);

  return open ? createPortal(children, selector) : null;
};

export const EditExerciseModal = ({ close }) => {
  return (
    <div>
      {/* Instead of creating a handler inside this component we can create it in it's parent element */}
      <span onClick={close}>X</span>
      {/* Content */}
    </div>
  );
};

export const ModalBtn = () => {
  const [isEditModalOpen, setEditModalOpen] = useState(false);
  // this is where it all comes together,
  // our button element will keep track of the isEditModalOpen variable,
  // which in turn will update  both child elements
  // when true useEffect hook will re-render Modal Component only now it "will" createPortal()
  // when our EditExerciseModal alls close it will set change the isEditModalOpen to false
  // which will be passed to the Modal component which
  // will then cause the component to re-render and not call createPortal()

  return (
    <>
      <button onClick={() => setEditModalOpen(true)}>EditExerciseModal</button>
      {setEditModalOpen && (
        <Modal
          open={isEditModalOpen}
          setOpen={setEditModalOpen}
          selector={'#portal'}>
          <div className='overlay'>
            <EditExerciseModal close={() => setEditModalOpen(false)} />
          </div>
        </Modal>
      )}
    </>
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda