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

74
Views
React function doesn't updated with state

I'm trying to execute a function that is using react state but when state changes the function doesn't updates with the state value.

    const {useState, useEffect} = React;

function Example() {
  const [count, setCount] = useState(0);
  
  const testFunction = function(){
        setInterval(() => {
        console.log(count)
    }, 3000)
  }
  useEffect(() => {
let fncs = [testFunction];

fncs.forEach(fnc => fnc.apply(this));
  }, [])
  


  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {   
    // Update the document title using the browser API    
    document.getElementById('other-div').innerHTML = `You clicked ${count} times`;  
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render( <Example />, document.getElementById('root') );

Exmaple: https://jsfiddle.net/bzyxqkwt/4/

just so you understand, im passing functions to another component and he execute those functions on some event like this

fncs.forEach(fnc => fnc.apply(this, someEventParams));
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I'm just guessing that the setInterval is just for demo purposes and needs to be stopped/removed, but basically useEffect captures the initial state. So if you want to catch inside the inner function updated state, then you should pass all the values that you need (in this case count parameter). Something like:

const testFunction = function(){
    // setInterval(() => {
        console.log(count); // it should log the updated value
    // }, 3000)
  }
  useEffect(() => {
     let fncs = [testFunction];

      fncs.forEach(fnc => fnc.apply(this));
  }, [count]);   // <-- this makes the trick
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!