Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

74
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!