I am binding a method to a button inside the useEffect hook, and the method internally is making use of state. But I am not getting the updated state inside the method to be binded instead getting state value as initialSate
If I pull the code outside the useEffect hook, everything works fine but not sure if this is the correct way.
function Test() {
const initialState = { name: ''}
const reducer = () => {...}
const [state, dispatch] = useReducer(reducer, initialState);
const save = (): void => {
...
const { name } = state;
// here i am getting state value as the initialState and not the
// updated state value
...
}
useEffect(() => {
...
bindActionToButton(button, save);
...
}, []);
}
The save method is bound to the click event of the button.On clicking the button, the value of state inside the state should be the updated state value but I am getting value as initalState value. If I call pull the code outside the useEffect everything works fine.