Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: useState hook to provide a ref for callbacks #24729

Closed
WouterVanheeswijk-TomTom opened this issue Jun 15, 2022 · 2 comments
Closed
Labels
Resolution: Duplicate Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug

Comments

@WouterVanheeswijk-TomTom
Copy link

WouterVanheeswijk-TomTom commented Jun 15, 2022

Problem

I often find that when I'm using useState together with useCallback, that my callbacks depend on the current state:

const [state, setState] = useState(initialState);

const myCallback = useCallback(
  () => {
    // .. do something with current `state`, other than purely updating it:
    fetch(`https://example.com/${state}`);
  },
  [state] // need a dependency on `state`
);

return <>
  <MyComponent callback={myCallback}>
</>;

This gives unnecessary performance issues, because my callback is updated with each state update. Depending on the situation of the state and the components that take myCallback as a prop, it can get pretty bad.

Current workaround

I'm finding myself often doing this, to avoid such performance penalties:

const [state, setState] = useState(initialState);
const stateRef = useRef(state);

// effect's job is purely to update the `stateRef`
useEffect(
  () => stateRef.current = state,
  [state]
);

const myCallback = useCallback(
  () => {
    // use `stateRef` instead
    fetch(`https://example.com/${stateRef.current}`);
  },
  [] // can now be empty
);

Possible improvement

What I would like to suggest, is that useState provides a way to access the current value for callbacks. E.g.:

const [state, setState, stateRef] = useState(initialState);

// now I can use stateRef.current for my callbacks

Any thoughts?

@Takal-H
Copy link

Takal-H commented Jun 16, 2022

good idea

@eps1lon
Copy link
Collaborator

eps1lon commented Jun 16, 2022

Closing in favor of reactjs/rfcs#201.

But you probably want to take a look at reactjs/rfcs#220 instead which has the same goal as the issue you're describing here (useCallback invalidation) but with a different proposal.

@eps1lon eps1lon closed this as not planned Won't fix, can't repro, duplicate, stale Jun 16, 2022
@eps1lon eps1lon added Resolution: Duplicate Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug labels Jun 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Resolution: Duplicate Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug
Projects
None yet
Development

No branches or pull requests

3 participants