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

178
Views
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
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!