Skip to content

Stale-props-free useSelector #43

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Change Log

## [Unreleased]
### Changed
- useSelector avoids stale props without try-catch mitigation

## [4.4.0] - 2019-10-17
### Added
Expand Down
73 changes: 73 additions & 0 deletions __tests__/03_stale_props.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React from 'react';
import { createStore } from 'redux';

import { render, cleanup, act } from '@testing-library/react';

import { Provider, useSelector } from '../src/index';

describe('stale props spec', () => {
afterEach(cleanup);

it('ignores transient errors in selector (e.g. due to stale props)', () => {
const Parent = () => {
const count = useSelector((state) => state.count);
return <Child parentCount={count} />;
};

const Child = ({ parentCount }) => {
const selector = (state) => {
if (state.count !== parentCount) {
throw new Error();
}
return state.count + parentCount;
};
const result = useSelector(selector);
return <div>{result}</div>;
};

const store = createStore((state = { count: -1 }) => ({ count: state.count + 1 }));

const App = () => (
<Provider store={store}>
<Parent />
</Provider>
);

render(<App />);
act(() => {
expect(() => store.dispatch({ type: '' })).not.toThrowError();
});
});

it('ensures consistency of state and props in selector', () => {
let selectorSawInconsistencies = false;

const Parent = () => {
const count = useSelector((state) => state.count);
return <Child parentCount={count} />;
};

const Child = ({ parentCount }) => {
const selector = (state) => {
selectorSawInconsistencies = selectorSawInconsistencies || (state.count !== parentCount);
return state.count + parentCount;
};
const result = useSelector(selector);
return <div>{result}</div>;
};

const store = createStore((state = { count: -1 }) => ({ count: state.count + 1 }));

const App = () => (
<Provider store={store}>
<Parent />
</Provider>
);

render(<App />);
act(() => {
store.dispatch({ type: '' });
});
expect(selectorSawInconsistencies).toBe(false);
});
});
39 changes: 7 additions & 32 deletions src/useSelector.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import {
useContext,
useEffect,
useRef,
useReducer,
} from 'react';
import { useContext, useEffect, useReducer } from 'react';

import { defaultContext } from './Provider';

import { useIsomorphicLayoutEffect } from './utils';

const isFunction = (f) => typeof f === 'function';
const defaultEqualityFn = (a, b) => a === b;

Expand All @@ -17,32 +10,14 @@ export const useSelector = (selector, eqlFn, opts) => {
equalityFn = isFunction(eqlFn) ? eqlFn : defaultEqualityFn,
customContext = defaultContext,
} = opts || (!isFunction(eqlFn) && eqlFn) || {};
const [, forceUpdate] = useReducer((c) => c + 1, 0);
const { state, subscribe } = useContext(customContext);
const selected = selector(state);
const ref = useRef(null);
useIsomorphicLayoutEffect(() => {
ref.current = {
equalityFn,
selector,
state,
selected,
};
});
const [selected, updateSelected] = useReducer((prevSelected) => {
const nextSelected = selector(state);
if (equalityFn(prevSelected, nextSelected)) return prevSelected;
return nextSelected;
}, state, selector);
useEffect(() => {
const callback = (nextState) => {
try {
if (ref.current.state === nextState
|| ref.current.equalityFn(ref.current.selected, ref.current.selector(nextState))) {
// not changed
return;
}
} catch (e) {
// ignored (stale props or some other reason)
}
forceUpdate();
};
const unsubscribe = subscribe(callback);
const unsubscribe = subscribe(updateSelected);
return unsubscribe;
}, [subscribe]);
return selected;
Expand Down