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

Allow useSelector without provider #2080

Closed
OldStarchy opened this issue Nov 8, 2023 · 1 comment
Closed

Allow useSelector without provider #2080

OldStarchy opened this issue Nov 8, 2023 · 1 comment

Comments

@OldStarchy
Copy link

What is the new or updated feature that you are suggesting?

Allow using useSelector outside a provider, in which case return either a default value as defined by the context, undefined, or a noop function.

Why should this feature be included?

Some parts of our application have text fields that trigger a "currently highlighted field" value when it receives focus.

For example (similar to our use case): focusing the field for the name of a player will highlight their profile icon, this "currently selected player" information is handled in a uiStore with onFocus={() => dispatch(actions.setFocusedField(id))}.

The highlighting is not critical to the operation of the text field. If there is no available uiStore it's fine to continue without it, but useReduxContext (as called by useSelector / useDispatch will throw an error.

I tried using useStore directly but this also throws, and would leave me without the functionality provided by useSelector.

What docs changes are needed to explain this?

I could not find the reason for this restriction in the docs.

@markerikson
Copy link
Contributor

React-Redux has always relied on accessing the store via React context. It's effectively a form of dependency injection, which enables separating the question of "which store is this component reading from?" from the actual specific store instance. Otherwise, you'd be locking yourself into a single store that's being imported directly from a module. (You'd also have to somehow pass that store instance into every call to useSelector and useDispatch.)

For connect specifically, it also relies on the context hierarchy to ensure the invariant that a given component's mapState function only runs after its nearest connected ancestor has updated, to ensure it has the freshest props available as ownProps inside of mapState.

We have no plans to change this.

If some of your components can somehow be used without a Redux store available, then you probably need to rewrite them to separate out which pieces do rely on Redux vs which pieces do not (such as having a parent component that reads dispatch from the Redux store and passes it down as a prop to the child).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants