score:0

Accepted answer

Issue

const toggleButton1 = () => {
  setState({
    number : 4,
    callback : () => {
      console.log('state number', state.number);
      console.log('second number', secondNumber);
    }
  })
}

This encloses the current state and secondNumber values from the current render cycle in the stored callback. Invoking it later will use the value when stored.

Solution

Simply do in the effect hook what you want to do with the updated state. Functional component state updates don't really have an equivalent of the class-based component's setState callback parameter, the useEffect with appropriate dependency is its equivalent.

function App(){
  const [state, setState] = useState({
    number : 2,
    callback : null
  });
  let secondNumber = 10;

  useEffect(() => {
    console.log('state number', state.number);
    console.log('second number', secondNumber);
  }, [state.number]);

  const toggleButton1 = () => {
   setState({
     number : 4,
   })
  }
  
  return (
    //button trigger function toggleButton1
  )
}

export default App;

FYI, as defined, secondNumber will be reset/redefined back to 10 each render cycle, you can mutate it within each cycle but it'll be reset each time.


Related Query

More Query from same tag