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

137
Visualizações
useEffect dependency is not updating the useEffect

I have a useEffect hook that is not updating after changing the dependency. The dependency is a state variable passed through props. Included below is what the code looks like:

const MyComponent = ({resource}) => {

// runs after changing resource state
console.log(resource)

useEffect(() => {
    setLoading(true);
      // doesnt run after changing resource state
      console.log(resource)
      setVariable(setDefaultValue());
    
  }, [resource]);

}

MyComponent is being rendered for one of two states 'option1' or 'option2' the component renders differently depending on the state. I call the component like so:

const [resource, setResource] = useState('option1');
const handleChange = (e) => {
    setResource(e.target.value);
};

return (
    <MyComponent resource={resource} />
)

I don't understand why the useEffect isn't running after resource state is changed. The console.log on the outside of the useEffect show the change state, but the console.log inside of the useffect isn't run after changing state.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Oh, you can change code the following above try:

//Parent Component
const [resource, setResource] = useState('option1');
const [variable,setVariable] = useState();
const [loading,setLoading] = useState(false);
useEffech(()=>{
  let fetch_api = true;
  setLoading(true);
  fetch(URL,options).then(res=>res.json())
    .then(res=>{
       if(fetch_api){
          setVariable(setDefaultValue());
          setLoading(false);
       }
    });
    return ()=>{
        //remove memory
        fetch_api = false;
    }
},[resource]);
const handleChange = (e) => {
    setResource(e.target.value);
};

return (
    <MyComponent variable={variable} />
)


//Child Component
const MyComponent=({variable})=>{
  
  return <>
    
  </>
}

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