-2

Similar to:

So say I have a notify() method that I want to be fired AFTER the states have changed, not during state change. Also after I click.

something like

const handleClick = useCallback(()=>{
  const [state,setState] = useState("bar");
  ...
  setState("foo", ()=> {
  ... at this point `state` should be "foo" ...;
  notify("yo we're set. but I am not passing the current state to you");
  })
});
...

a component that is child of the context

const { state } = useSomeContext();
subscribe(()=>{
  console.log("I want ", state, " to be the updated value, but I get the existing value); 
});
  • useStateRef lets the callback know but the ones listening when they query the value that is in the state may not get the updated value.
  • useStateCallback does not solve the problem for me either because it's the callback that has the value.

The workaround I sort of ended up with (still testing it) is to utilize a useRef to the value somewhat like useStateRef and do stateRef.current instead of just state

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
  • 1
    The answers to https://stackoverflow.com/q/56247433/3001761 do use function-based components, hooks don't work in class-based components – jonrsharpe Feb 03 '23 at 00:16
  • `useEffect` as mentioned in the answer linked by both of you is indeed the way to go here. You mentioned "another component", but it's unclear whether that would be a parent, sibling, or child. Depending on the case, the react team has been discouraging `useEffect` lately, and recommending calling callbacks from the same action that calls the `useEffect` instead – Ben Wong Feb 03 '23 at 00:20

1 Answers1

0

When you change the state via the setter, it will cause the current component to re-render. If the component you want to 'notify' is within the current component and has a dependency on the state value that changed e.g.:

return (
  <>
    <SomeOtherComponent something={state}/>
  </>
)

... then that component will re-render as well.

If the component you want to notify isn't in the render path, you can make the state a dependency of a useEffect so your useEffect will run whenever the state change (and do your notification there). You can have multiple useEffects with with dependencies on different state. Example:

useEffect(()=> {
  console.log('hello, state is',state)
}, [state])

And you can look into context and other mechanisms to communicate state. You should read this article. I think it's very inline with what you'd like to do.

Certainly don't do anything in your useState setter other than the minimal needed to return the new state.

Dave
  • 7,552
  • 4
  • 22
  • 26