Skip to content

Commit da4e446

Browse files
MrWolfZtimdorr
authored andcommitted
fix timing issue with setting up store subscription inside a connected component; see issue 1226 (reduxjs#1235)
1 parent c033114 commit da4e446

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/components/connectAdvanced.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ export default function connectAdvanced(
291291
})
292292

293293
// Our re-subscribe logic only runs when the store/subscription setup changes
294-
useEffect(() => {
294+
useIsomorphicLayoutEffect(() => {
295295
// If we're not subscribed to the store, nothing to do here
296296
if (!shouldHandleStateChanges) return
297297

test/components/connect.spec.js

+32
Original file line numberDiff line numberDiff line change
@@ -1926,6 +1926,38 @@ describe('React', () => {
19261926

19271927
expect(mapStateToProps).toHaveBeenCalledTimes(2)
19281928
})
1929+
1930+
it('should not notify nested components after they are unmounted', () => {
1931+
@connect(state => ({ count: state }))
1932+
class Parent extends Component {
1933+
render() {
1934+
return this.props.count === 1 ? <Child /> : null
1935+
}
1936+
}
1937+
1938+
const mapStateToProps = jest.fn(state => ({ count: state }))
1939+
@connect(mapStateToProps)
1940+
class Child extends Component {
1941+
render() {
1942+
return <div>{this.props.count}</div>
1943+
}
1944+
}
1945+
1946+
const store = createStore((state = 0, action) =>
1947+
action.type === 'INC' ? state + 1 : state
1948+
)
1949+
rtl.render(
1950+
<ProviderMock store={store}>
1951+
<Parent />
1952+
</ProviderMock>
1953+
)
1954+
1955+
expect(mapStateToProps).toHaveBeenCalledTimes(0)
1956+
store.dispatch({ type: 'INC' })
1957+
expect(mapStateToProps).toHaveBeenCalledTimes(1)
1958+
store.dispatch({ type: 'INC' })
1959+
expect(mapStateToProps).toHaveBeenCalledTimes(1)
1960+
})
19291961
})
19301962

19311963
describe('Custom context and store-as-prop', () => {

0 commit comments

Comments
 (0)