UseEffect doesn't run after state updated
See original GitHub issueCurrent behavior
Value is the old value of ‘Start’
Expected behavior
Value is the new value of ‘clicked’
Your environment
Windows
API
- mount
Version
library | version |
---|---|
enzyme | 3.9.0 |
react | 16.8.6 |
react-dom | 16.8.6 |
react-test-renderer | 16.8.6 |
adapter (below) | 1.12.1 |
Adapter
- enzyme-adapter-react-16
import React, { useEffect, useState } from 'react';
import { mount } from 'enzyme';
export const MyComponent = () => {
const [value, setValue] = useState('start');
const [mirror, setMirror] = useState('');
useEffect(() => {
console.log(`useEffect sees value of ${value}`);
setMirror(value);
}, [value]);
return (
<div>
<button onClick={() => setValue('clicked')} />
<span>{value}</span>
<p>{mirror}</p>
</div>
);
};
it('renders updated values', () => {
const wrapper1 = mount(<MyComponent />);
console.log('Simulating Click');
wrapper1.find('button').simulate('click');
console.log('Simulated Click');
expect(wrapper1.find('span').text()).toContain('clicked');
expect(wrapper1.find('p').text()).toContain('clicked');
});
Issue Analytics
- State:
- Created 4 years ago
- Comments:16 (9 by maintainers)
Top Results From Across the Web
useEffect Hook Not Firing After State Change - Stack Overflow
The useEffect hook is only fired on the initial render, though the state of arr updates. I know that declaring a new variable...
Read more >React.useEffect Hook – Common Problems and How to Fix ...
Let's start with a simple scenario. We are building a React app and we want to display the user name of the current...
Read more >an effect doesn't run again when its dependencies change
It seems to be pretty simple on the surface. After all, it just tells React to "re-run this function when one of these...
Read more >How the useEffect Hook Works (with Examples) - Dave Ceddia
Run useEffect on State Change ... By default, useEffect runs after every render, but it's also perfect for running some code in response...
Read more >Are you logging the state immediately after updating it? Here's ...
When logging inside useEffect , you're using the state value that was captured in the closure at the beginning of the render. So...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
As a workaround you could call
This has the effect that internally a rerender happens and your effect runs.
I find
update
doesn’t rerender a functional component - butsetProps
does.