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

141
Views
Why is the default value of the useState hooks undefined?

I have a list of graphics received from redux state. I have also created a state hook whose default value is the first object in this list. Why is the variable currentFile undefined ? I searched for similar topics that would explain this issue to me, but I didn't find anything similar. The strange thing is that when I display the default value itself in the console I get the expected result. When I type a number in the index of the image list, e.g. images[0], I also get an undefined value.

Below I put a picture of the console result.

enter image description here

Code:

function Images() {
  const [activeIdx, setActiveIdx] = useState(0)

  const dispatch = useDispatch()

  const imagesList = useSelector((state) => state.imagesList)
  const { loading, error, images } = imagesList

  const [currentFile, setCurrentFile] = useState(images[activeIdx])

  console.log(images[activeIdx])

  console.log(currentFile)

    useEffect(() => {
    dispatch(listImages())
  }, [dispatch)

  return (
     ...
  )
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

useState(initialValue) will only use initialValue on the first render and does not change after re-renders. graphics[activeIdx] can be undefined so this will log undefined as a currentFile value.

You should write listener which will save every new value of graphics[activeIdx] to your state:

useEffect(() => {
     setCurrentFile(images[activeIdx])
  }, [images])
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!