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

156
Vistas
useEffect wont run when state gets changed

Why doesn't useEffect run when sorting gets changed? I only want it to run when sorting.options get adjusted, but for some reason, when I add options to sorting.options the useEffect won't run happen; however, when I only have "sorting" it works perfectly even though only options get changed in handleChange? I dont want to have only sorting in there because I don't want the useEffect to run when sorting.value gets changed, for example.

const handleChange=index=>event=>{
    let newOptions = sorting.options
    newOptions[index]["value"]=event.target.value
    setSorting((prevState)=>({
      ...prevState,
      options:newOptions
    }))
    console.log("sorting changed")
  }
  useEffect(()=>{
    console.log("Change happend")
  },[sorting.options])//This works perfectly fine when only sorting is there, but when i put in sorting.options nothing happens
about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

As Quentin said, try

let newOptions = sorting.options.slice(0)

To copy the options array instead of mutating it

about 4 years ago · Santiago Gelvez Denunciar

0

The problem is that you keep the reference of the original object throughout different render. Just replace by a copy

import React, { useState, useEffect } from "react";

export default function Home() {
  const [sorting, setSorting] = useState({
    options: { 1: { value: 2 } },
    email: "vapa@dieheli.us",
  });

  const handleChange = (index) => (event) => {
    let newOptions = sorting.options; // Here you are getting the reference of sorting.opions which is constant between renders
    // let newOptions = { ...sorting.options }; // Just replace previous line for a copy. 
    newOptions[index]["value"] = event.target.value; // Then you mutated the same object
    setSorting((prevState) => ({
      // setSorting creates a new object reference
      ...prevState,
      options: newOptions, // but options references never changed
    }));
  };

  useEffect(() => {
    console.log("Change happend", sorting);
  }, [sorting.options]);

  return (
    <div>
      Home <input onChange={handleChange(1)} />
    </div>
  );
}
about 4 years ago · Santiago Gelvez 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