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

179
Visualizações
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 à 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