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

77
Visualizações
useState keeps initial state after defining it in useEffect

I have an async function that fetches some data from an API. Since I need that data to properly load my component I decided to fetch the data in the useEffect and then store it in a useState what works just fine. However, if I try to console log it, it just shows its initial state what technically would mean it's still unset or that the console log runs before assigning the useState.

Thanks for your help in advance.

const [categories, setCategories] = useState([])

useEffect(() => {
    fetchListProductCats().then(function(result){
        setCategories(result.data)
    })
    console.log(categories) // returns -> []
    
}, []);

if(!categories.length){
    return "loading"
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

async function with Promise, make sure you know what it means.

The console.log line in this code always runs before the Promise resolved.

If you want to observe the changing of categories, use another useEffect:

useEffect(() => {
  console.log(categories);
}, [categories]);
about 4 years ago · Juan Pablo Isaza Relatório

0

Your state is already updated with data you wanted its showing categories with it's initial values because you have rendered useEffect with no dependancies. And it is consoled befored being updated. Try using below code snippets to log.

useEffect(() => {
    console.log(categories)
}, [categories]);
about 4 years ago · Juan Pablo Isaza Relatório

0

React setState is async. It won't update immediately after calling the function. It will go through a re-rendering process first to update the user interface. Once re-rendering is done, the functions provided in the useEffect hook will be called.

useEffect(()=>{
  console.log(categories)
}, [categories]) 
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