useLayoutEffect gets the initial state from useState instead of the current state when its input list never changes when an async method is fired
See original GitHub issueDo you want to request a feature or report a bug?
Report a bug.
What is the current behavior?
When using useLayoutEffect
(having it fire only once during mount, and once during unmount), setting state outside of it and then having an async method run inside of it, results in it not being able to useState
as expected. Instead of getting the latest value - it always gets the initial value.
Codesandbox here: https://codesandbox.io/s/9jm66px2z4 Actual usage here: https://github.com/madou/react-peer/blob/master/src/use-peer-state.tsx#L29
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn’t have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:
What is the expected behavior?
That it would get the current state when the async code is run. If I don’t supply a input list to the hook it works as expected - however at the cost of repeated cleanup/initialisation.
I’m looking from the synonymous componentDidMount()
/componentWillUnmount()
hooks - was thinking using useLayoutEffect
like so would do it.
Am I using it as expected? Is there a proper way to use it?
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
Using 16.8.0-alpha.1
.
Cheers,
Issue Analytics
- State:
- Created 5 years ago
- Reactions:2
- Comments:6 (3 by maintainers)
thanks both - have some good ideas to think about. also need to remember hooks aren’t magical and closure rules apply… 😄
I think they also mentioned to not use it unless you actually have problems. 😃 It makes your app slower. Just like cDM/cDU which block paint.