-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Fix #91: Add Typing connect() Factory Functions section to README #314
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
Open
gfgf-brain
wants to merge
3
commits into
piotrwitek:master
Choose a base branch
from
gfgf-brain:brain-fix-91
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+153
−0
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -2247,6 +2247,159 @@ Higher-Order Components: | |||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| --- | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ## Typing connect() Factory Functions | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| React-Redux's `connect()` accepts a **factory function** form of `mapStateToProps` and `mapDispatchToProps`. When you return a function instead of an object, React-Redux calls it once per component instance — enabling per-instance memoization with `reselect`. | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| The challenge is typing the factory correctly. React-Redux exports `MapStateToPropsFactory` and `MapDispatchToPropsFactory` for exactly this purpose. | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ### MapStateToPropsFactory | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ```typescript | ||||||||||||||||||||||||||||
| import { connect, MapStateToPropsFactory } from 'react-redux'; | ||||||||||||||||||||||||||||
| import { createSelector } from 'reselect'; | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| interface OwnProps { | ||||||||||||||||||||||||||||
| userId: string; | ||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| interface StateProps { | ||||||||||||||||||||||||||||
| username: string; | ||||||||||||||||||||||||||||
| isActive: boolean; | ||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| interface RootState { | ||||||||||||||||||||||||||||
| users: Record<string, { name: string; active: boolean }>; | ||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| // Factory: called once per component instance. | ||||||||||||||||||||||||||||
| // Returns the actual mapStateToProps for that instance. | ||||||||||||||||||||||||||||
| const makeMapStateToProps: MapStateToPropsFactory<StateProps, OwnProps, RootState> = | ||||||||||||||||||||||||||||
| () => { | ||||||||||||||||||||||||||||
| // Each instance gets its own memoized selector — no cross-instance cache invalidation. | ||||||||||||||||||||||||||||
| const selectUser = createSelector( | ||||||||||||||||||||||||||||
| (state: RootState) => state.users, | ||||||||||||||||||||||||||||
| (_: RootState, ownProps: OwnProps) => ownProps.userId, | ||||||||||||||||||||||||||||
| (users, id) => users[id], | ||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| return (state, ownProps) => { | ||||||||||||||||||||||||||||
| const user = selectUser(state, ownProps); | ||||||||||||||||||||||||||||
| return { | ||||||||||||||||||||||||||||
| username: user?.name ?? 'Unknown', | ||||||||||||||||||||||||||||
| isActive: user?.active ?? false, | ||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| export default connect(makeMapStateToProps)(MyComponent); | ||||||||||||||||||||||||||||
| ``` | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ### MapDispatchToPropsFactory | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ```typescript | ||||||||||||||||||||||||||||
| import { Dispatch } from 'redux'; | ||||||||||||||||||||||||||||
| import { MapDispatchToPropsFactory } from 'react-redux'; | ||||||||||||||||||||||||||||
| import { updateUser, deleteUser } from './actions'; | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| interface OwnProps { | ||||||||||||||||||||||||||||
| userId: string; | ||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| interface DispatchProps { | ||||||||||||||||||||||||||||
| onUpdate: (name: string) => void; | ||||||||||||||||||||||||||||
| onDelete: () => void; | ||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| const makeMapDispatchToProps: MapDispatchToPropsFactory<DispatchProps, OwnProps> = | ||||||||||||||||||||||||||||
| () => (dispatch: Dispatch, ownProps: OwnProps) => ({ | ||||||||||||||||||||||||||||
| onUpdate: (name) => dispatch(updateUser({ id: ownProps.userId, name })), | ||||||||||||||||||||||||||||
| onDelete: () => dispatch(deleteUser({ id: ownProps.userId })), | ||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| export default connect(makeMapStateToProps, makeMapDispatchToProps)(MyComponent); | ||||||||||||||||||||||||||||
| ``` | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ### Why Not Just Skip the Return Type? | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| Omitting the return type annotation works at runtime but loses type safety: | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ```typescript | ||||||||||||||||||||||||||||
| // ❌ Works, but TypeScript cannot check the factory's return type | ||||||||||||||||||||||||||||
| const makeMapState = () => (state: RootState, ownProps: OwnProps) => ({ | ||||||||||||||||||||||||||||
| username: state.users[ownProps.userId]?.name, | ||||||||||||||||||||||||||||
| // typo: `usrname` would silently pass as `string | undefined` without return type | ||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| // ✅ Explicit return type — errors caught at the factory definition, not at use-site | ||||||||||||||||||||||||||||
| const makeMapState: MapStateToPropsFactory<StateProps, OwnProps, RootState> = () => | ||||||||||||||||||||||||||||
| (state, ownProps) => ({ | ||||||||||||||||||||||||||||
| username: state.users[ownProps.userId]?.name ?? 'Unknown', | ||||||||||||||||||||||||||||
| isActive: state.users[ownProps.userId]?.active ?? false, | ||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||
| ``` | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ### Full Typed Component | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ```typescript | ||||||||||||||||||||||||||||
| import React from 'react'; | ||||||||||||||||||||||||||||
| import { Dispatch } from 'redux'; | ||||||||||||||||||||||||||||
| import { connect, MapStateToPropsFactory } from 'react-redux'; | ||||||||||||||||||||||||||||
| import { createSelector } from 'reselect'; | ||||||||||||||||||||||||||||
| import { deleteUser } from './actions'; | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| interface RootState { | ||||||||||||||||||||||||||||
| users: Record<string, { name: string; active: boolean }>; | ||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
|
Comment on lines
+2345
to
+2355
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The
Suggested change
|
||||||||||||||||||||||||||||
| // Own props passed to the component from outside | ||||||||||||||||||||||||||||
| interface OwnProps { userId: string; } | ||||||||||||||||||||||||||||
| // Props injected by mapStateToProps | ||||||||||||||||||||||||||||
| interface StateProps { username: string; isActive: boolean; } | ||||||||||||||||||||||||||||
| // Props injected by mapDispatchToProps | ||||||||||||||||||||||||||||
| interface DispatchProps { onDelete: () => void; } | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| type Props = OwnProps & StateProps & DispatchProps; | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| const UserCard: React.FC<Props> = ({ username, isActive, onDelete }) => ( | ||||||||||||||||||||||||||||
| <div className={isActive ? 'active' : 'inactive'}> | ||||||||||||||||||||||||||||
| <span>{username}</span> | ||||||||||||||||||||||||||||
| <button onClick={onDelete}>Remove</button> | ||||||||||||||||||||||||||||
| </div> | ||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| const makeMapState: MapStateToPropsFactory<StateProps, OwnProps, RootState> = () => { | ||||||||||||||||||||||||||||
| const sel = createSelector( | ||||||||||||||||||||||||||||
| (s: RootState) => s.users, | ||||||||||||||||||||||||||||
| (_: RootState, p: OwnProps) => p.userId, | ||||||||||||||||||||||||||||
| (users, id) => users[id], | ||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||
| return (state, ownProps) => { | ||||||||||||||||||||||||||||
| const user = sel(state, ownProps); | ||||||||||||||||||||||||||||
| return { | ||||||||||||||||||||||||||||
| username: user?.name ?? 'Unknown', | ||||||||||||||||||||||||||||
| isActive: user?.active ?? false, | ||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| const mapDispatch = (dispatch: Dispatch, { userId }: OwnProps): DispatchProps => ({ | ||||||||||||||||||||||||||||
| onDelete: () => dispatch(deleteUser({ id: userId })), | ||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| export default connect(makeMapState, mapDispatch)(UserCard); | ||||||||||||||||||||||||||||
| ``` | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| ### When to Use Factory Functions | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| | Use case | Use factory? | | ||||||||||||||||||||||||||||
| |---|---| | ||||||||||||||||||||||||||||
| | Simple derived data, one instance on screen | No — plain `mapStateToProps` is fine | | ||||||||||||||||||||||||||||
| | Same component rendered in a list (multiple instances) | **Yes** — separate selector cache per item | | ||||||||||||||||||||||||||||
| | mapStateToProps that depends on `ownProps` in a selector | **Yes** — prevents cache thrashing | | ||||||||||||||||||||||||||||
| | `mapDispatchToProps` that binds `ownProps` into action creators | Yes, or use `bindActionCreators` | | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| # Contributors | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
OwnPropsinterface is used in this code block but is not defined or imported, which will cause compilation errors if a user copies and pastes this snippet. Defining it here makes the example self-contained.