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

134
Vistas
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 Respuestas
Responde la pregunta

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 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