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

180
Vistas
Accessing child state and calling method with useImperativeHandle hook React

In my app I have 2 components, looking like this:

  1. Child component
import React, { useState, useImperativeHandle } from 'react'

const Child = React.forwardRef(({props}, ref) => {
  const [loading, setLoading] = useState(false)
  const [text, setText] = useState('')

  const increment = () => {
    setLoading(true)
    sayHello()
    console.log(text)
    setLoading(false)
  }

  const sayHello = () => {
    const string = 'hello'
    setText(string)
  }

  useImperativeHandle(ref, () => ({
    increment
  }))

  return (
    <div>
      {loading ? <div>Loading...</div> : null}
      <h4>Child component</h4>
    </div>
  )
})

export default Child
  1. Parent component
import React, { useRef } from 'react'
import Child from './Child'

function Parent() {
  const childComponent = useRef();

  return (
    <div>
      <h1>Parent</h1>
      <Child ref={childComponent}/>
      <button onClick={(e)=>{e.preventDefault(); childComponent.current.increment()}}>Click me</button>      
    </div>
  )
}

export default Parent

What I am trying to achieve is to call a Child component method and get the text value displayed which is set in Child state.

Instead, when executing the increment() function the first time the console prints an empty string. Only on second button press it prints 'hello'.

What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
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