### Start Development Server
Source: https://github.com/reduxjs/react-redux/blob/master/website/README.md
Use this command to start the Docusaurus development server and preview your site.
```sh
# Start the site
$ yarn start
```
--------------------------------
### Install Project Dependencies with Yarn
Source: https://github.com/reduxjs/react-redux/blob/master/CONTRIBUTING.md
After cloning the repository, install all necessary project dependencies using Yarn. Ensure Yarn v1.22 is installed globally first.
```bash
yarn install
```
--------------------------------
### Install Dependencies with Yarn
Source: https://github.com/reduxjs/react-redux/blob/master/website/README.md
Run this command to install all necessary dependencies for the Docusaurus website.
```sh
# Install dependencies
$ yarn
```
--------------------------------
### Run Development Server
Source: https://github.com/reduxjs/react-redux/blob/master/examples/publish-ci/rr-rsc-context/README.md
Use npm, yarn, or pnpm to start the development server for the Next.js application.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
```
--------------------------------
### Install Redux Toolkit and React Redux
Source: https://github.com/reduxjs/react-redux/blob/master/docs/tutorials/quick-start.md
Add the necessary Redux packages to your project using npm.
```sh
npm install @reduxjs/toolkit react-redux
```
--------------------------------
### Install React Redux in an Existing App
Source: https://github.com/reduxjs/react-redux/blob/master/docs/introduction/getting-started.md
Add React Redux to your project using npm or Yarn. Ensure you also have Redux installed and a store configured.
```bash
# If you use npm:
npm install react-redux
# Or if you use Yarn:
yarn add react-redux
```
--------------------------------
### Create React Redux App with Vite Template
Source: https://github.com/reduxjs/react-redux/blob/master/README.md
Use this command to start a new React application with Redux Toolkit and React-Redux pre-configured using Vite.
```bash
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app
```
--------------------------------
### Create React Redux App with Next.js Template
Source: https://github.com/reduxjs/react-redux/blob/master/README.md
Use this command to start a new Next.js application with Redux integrated using the `with-redux` template.
```bash
npx create-next-app --example with-redux my-app
```
--------------------------------
### Full Manual Typing of connect in React-Redux
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/usage-with-typescript.md
Use this example when manually typing all prop sources for the `connect` HOC. Ensure all necessary interfaces and types are defined.
```tsx
import { connect } from 'react-redux'
interface StateProps {
isOn: boolean
}
interface DispatchProps {
toggleOn: () => void
}
interface OwnProps {
backgroundColor: string
}
type Props = StateProps & DispatchProps & OwnProps
const mapState = (state: RootState) => ({
isOn: state.isOn,
})
const mapDispatch = {
toggleOn: () => ({ type: 'TOGGLE_IS_ON' }),
}
const MyComponent = (props: Props) => (
)
// Typical usage: `connect` is called after the component is defined
export default connect(
mapState,
mapDispatch,
)(MyComponent)
```
--------------------------------
### Install React Redux with Yarn
Source: https://github.com/reduxjs/react-redux/blob/master/README.md
Install React Redux as a dependency in your existing React application using Yarn. Requires React 18 or later.
```bash
yarn add react-redux
```
--------------------------------
### Install React Redux with npm
Source: https://github.com/reduxjs/react-redux/blob/master/README.md
Install React Redux as a dependency in your existing React application using npm. Requires React 18 or later.
```bash
npm install react-redux
```
--------------------------------
### Provider Setup
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/hooks.md
To use React Redux hooks, wrap your entire application in the `` component, making the Redux store available throughout the component tree.
```APIDOC
## Provider Setup
### Description
Wrap your application with the `` component to make the Redux store accessible to all components.
### Method
Component Rendering
### Endpoint
N/A (Component Integration)
### Request Example
```jsx
import { createStore } from 'redux';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
const store = createStore(rootReducer);
// As of React 18
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
,
);
```
### Response
N/A (Component Integration)
```
--------------------------------
### Dispatch Action on Button Click
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/hooks.md
Example of using `useDispatch` to dispatch an action when a button is clicked. The `dispatch` function reference is stable.
```jsx
import React from 'react'
import { useDispatch } from 'react-redux'
export const CounterComponent = ({ value }) => {
const dispatch = useDispatch()
return (
{value}
)
}
```
--------------------------------
### Dispatching Actions from Action Creators with mapDispatchToProps
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
This example shows how to dispatch actions created by action creator functions. It uses `dispatch` and returns functions that call `dispatch` with the results of action creators.
```javascript
const increment = () => ({ type: 'INCREMENT' })
const decrement = () => ({ type: 'DECREMENT' })
const reset = () => ({ type: 'RESET' })
const mapDispatchToProps = (dispatch) => {
return {
// dispatching actions returned by action creators
increment: () => dispatch(increment()),
decrement: () => dispatch(decrement()),
reset: () => dispatch(reset()),
}
}
```
--------------------------------
### Define Root State and Dispatch Types
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/usage-with-typescript.md
Infer RootState and AppDispatch types from the store itself for correct type updates. Export these types from your store setup file.
```typescript
import { configureStore } from '@reduxjs/toolkit'
// ...
const store = configureStore({
reducer: {
posts: postsReducer,
comments: commentsReducer,
users: usersReducer,
},
})
// highlight-start
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
// highlight-end
```
--------------------------------
### Connected Counter Component Example
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
A functional component that receives dispatchable props from `mapDispatchToProps` and displays a counter.
```javascript
function Counter({ count, increment, decrement, reset }) {
return (
{count}
)
}
```
--------------------------------
### Redux action creator example
Source: https://github.com/reduxjs/react-redux/blob/master/docs/tutorials/connect.md
Defines an `addTodo` action creator that returns an object with a `type` and a `payload`. This action creator is used to add new todos to the Redux store.
```javascript
// redux/actions.js
import { ADD_TODO } from './actionTypes'
let nextTodoId = 0
export const addTodo = (content) => ({
type: ADD_TODO,
payload: {
id: ++nextTodoId,
content,
},
})
```
--------------------------------
### Connecting component without mapDispatchToProps
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
Example of connecting a component to the Redux store without explicitly defining mapDispatchToProps. The component will receive dispatch by default.
```javascript
connect()(MyComponent)
```
```javascript
connect(mapState)(MyComponent)
```
```javascript
connect(mapState, null, mergeProps, options)(MyComponent)
```
--------------------------------
### Provide Redux Store to React App
Source: https://github.com/reduxjs/react-redux/blob/master/docs/introduction/getting-started.md
Wrap your main `App` component with the `Provider` from `react-redux` to make the Redux store accessible. This setup is for React 18 and uses `ReactDOM.createRoot`.
```jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { Provider } from 'react-redux'
import store from './store'
import App from './App'
// As of React 18
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
,
)
```
--------------------------------
### Declarative Button Click Handler
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
This example shows how to make a button's `onClick` handler more declarative by calling a named function (`doSomething`) instead of directly dispatching an action. This abstracts away the knowledge of `dispatch` from the component.
```javascript
// button needs to be aware of "dispatch"
);
}
// fetch the corresponding store with connected components
// you need to use the correct context
connect(mapStateA, null, null, { context: ContextA })(MyComponentA)
// You may also pass the alternate context instance directly to the connected component instead
// it is possible to chain connect()
// in this case MyComponent will receive merged props from both stores
compose(
connect(mapStateA, null, null, { context: ContextA }),
connect(mapStateB, null, null, { context: ContextB })
)(MyComponent);
```
--------------------------------
### Create React Redux App with Vite or Next.js
Source: https://github.com/reduxjs/react-redux/blob/master/docs/introduction/getting-started.md
Use these commands to scaffold a new React application with Redux Toolkit and React-Redux pre-configured. Choose the Vite template for general React apps or the Next.js template for Next.js projects.
```bash
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app
```
```bash
npx create-next-app --example with-redux my-app
```
--------------------------------
### Setting Up Custom Context with React-Redux
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/hooks.md
Shows how to configure a custom React context for react-redux using `createStoreHook`, `createDispatchHook`, and `createSelectorHook`. This is useful for isolating stores in complex applications.
```javascript
import React from 'react'
import {
Provider,
createStoreHook,
createDispatchHook,
createSelectorHook,
} from 'react-redux'
const MyContext = React.createContext(null)
// Export your custom hooks if you wish to use them in other files.
export const useStore = createStoreHook(MyContext)
export const useDispatch = createDispatchHook(MyContext)
export const useSelector = createSelectorHook(MyContext)
const myStore = createStore(rootReducer)
export function MyProvider({ children }) {
return (
{children}
)
}
```
--------------------------------
### Get Redux Store Instance
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/hooks.md
The `useStore` hook returns a reference to the Redux store instance provided to the ``. Prefer `useSelector` for state access.
```typescript
import type { Store } from 'redux'
const store: Store = useStore()
```
--------------------------------
### Connecting Components with `connect` (Conceptual)
Source: https://github.com/reduxjs/react-redux/blob/master/etc/react-redux.dt-types.api.md
While the `connect` function itself is not detailed here, the types it uses for mapping state and dispatchToProps are documented.
```APIDOC
## State and Dispatch Mapping Types
### Description
These types define how to map Redux state and dispatch actions to your React component's props. They are fundamental to the `connect` higher-order component.
### MapStateToProps
**`MapStateToProps`**
A function that extracts specific pieces of state from the Redux store. It receives the entire state tree and the component's own props.
**`MapStateToPropsFactory`**
A factory function that returns a `MapStateToProps` function. Useful for creating `mapStateToProps` with initial configuration.
**`MapStateToPropsParam`**
Can be a `MapStateToProps` function, a `MapStateToPropsFactory`, `null`, or `undefined`.
### MapDispatchToProps
**`MapDispatchToPropsFunction`**
A function that receives the `dispatch` function and the component's own props, and returns an object of action creators or dispatchable objects.
**`MapDispatchToPropsNonObject`**
Can be a `MapDispatchToPropsFactory` or a `MapDispatchToPropsFunction`.
**`MapDispatchToPropsParam`**
Can be an object of action creators or a `MapDispatchToPropsNonObject` function.
### Options
**`Options`**
An interface for configuring the behavior of the `connect` higher-order component, including equality checks for props and state, and whether to use `pure` rendering.
- **`areStatePropsEqual`** ((nextStateProps: TStateProps, prevStateProps: TStateProps) => boolean) - Optional: Custom equality function for state props.
- **`areOwnPropsEqual`** ((nextOwnProps: TOwnProps, prevOwnProps: TOwnProps) => boolean) - Optional: Custom equality function for own props.
- **`areMergedPropsEqual`** ((nextMergedProps: TMergedProps, prevMergedProps: TMergedProps) => boolean) - Optional: Custom equality function for merged props.
- **`areStatesEqual`** ((nextState: State, prevState: State) => boolean) - Optional: Custom equality function for the entire state tree.
- **`pure`** (boolean) - Optional: If true, the component will not re-render if the props have not changed (default: true).
- **`forwardRef`** (boolean) - Optional: If true, the `ref` will be forwarded to the wrapped component (default: false).
```
--------------------------------
### connect() Return Value
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
Explains what the connect function returns and how to use it.
```APIDOC
## connect() Returns
The return of `connect()` is a wrapper function that takes your component and returns a wrapper component with the additional props it injects.
### Usage Example 1: Storing the HOC
```js
import { connect } from 'react-redux'
import { login, logout } from './actionCreators'
const mapState = (state) => state.user
const mapDispatch = { login, logout }
// First call: returns a HOC that you can use to wrap any component
const connectUser = connect(mapState, mapDispatch)
// Second call: returns the wrapper component with mergedProps
// You may use the HOC to enable different components to get the same behavior
const ConnectedUserLogin = connectUser(Login)
const ConnectedUserProfile = connectUser(Profile)
```
### Usage Example 2: Direct Usage
In most cases, the wrapper function will be called immediately:
```js
import { connect } from 'react-redux'
import { login, logout } from './actionCreators'
const mapState = (state) => state.user
const mapDispatch = { login, logout }
// Call connect to generate the wrapper function, and immediately call
// the wrapper function to generate the final wrapper component.
export default connect(mapState, mapDispatch)(Login)
```
```
--------------------------------
### connect() API
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
The connect() function signature and its parameters.
```APIDOC
## connect()
### Description
The `connect()` function connects a React component to a Redux store. It provides the component with data from the store and functions to dispatch actions.
### Method
N/A (Higher-Order Component)
### Endpoint
N/A
### Parameters
`connect` accepts four optional parameters:
1. **mapStateToProps** (`Function`): Optional. A function that maps the Redux store state to the component's props.
2. **mapDispatchToProps** (`Function | Object`): Optional. An object or function that maps Redux actions to the component's props.
3. **mergeProps** (`Function`): Optional. A function to merge the results of `mapStateToProps` and `mapDispatchToProps`.
4. **options** (`Object`): Optional. Configuration options for connect.
### mapStateToProps
#### Description
If provided, this function subscribes the component to Redux store updates. It is called whenever the store state changes.
#### Parameters
- **state** (Object) - The current Redux store state.
- **ownProps** (Object) - Optional. The props passed to the connected component.
#### Returns
- Object: A plain object that will be merged into the wrapped component's props.
### mapDispatchToProps
#### Description
This parameter can be an object or a function. If it's an object, each property is expected to be an action creator, and `connect` will automatically wrap them with `dispatch`. If it's a function, it receives `dispatch` and optionally `ownProps`.
#### Parameters (if function)
- **dispatch** (Function) - The Redux store's dispatch function.
- **ownProps** (Object) - Optional. The props passed to the connected component.
#### Returns (if function)
- Object: An object where keys are prop names and values are functions that dispatch actions.
```
--------------------------------
### Basic useSelector Usage
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/hooks.md
This is a basic example of using the `useSelector` hook to extract a single value from the Redux store. Ensure the `useSelector` hook is imported from 'react-redux'.
```jsx
import React from 'react'
import { useSelector } from 'react-redux'
export const CounterComponent = () => {
const counter = useSelector((state) => state.counter)
return
{counter}
}
```
--------------------------------
### Create New Blog Post
Source: https://github.com/reduxjs/react-redux/blob/master/website/README.md
Add a new blog post by creating a markdown file in `website/blog/` with the format `YYYY-MM-DD-Title.md` and including front matter like author and title.
```markdown
---
author: Frank Li
authorURL: https://twitter.com/foobarbaz
authorFBID: 503283835
title: New Blog Post
---
Lorem Ipsum...
```
--------------------------------
### mapStateToProps with ownProps
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-extracting-data-with-mapStateToProps.md
Example of `mapStateToProps` using `ownProps` to access component props for data retrieval. It retrieves a specific todo item based on its ID from props.
```typescript
function mapStateToProps(state, ownProps) {
const { visibilityFilter } = state
// ownProps would look like { "id" : 123 }
const { id } = ownProps
const todo = getTodoById(state, id)
// component receives additionally:
return { todo, visibilityFilter }
}
```
--------------------------------
### Set up Provider Component
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/hooks.md
Wrap your entire application in the `` component to make the Redux store available throughout the component tree. This is required before using any React Redux hooks.
```jsx
const store = createStore(rootReducer)
// As of React 18
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
,
)
```
--------------------------------
### Accessing Store Directly with useStore
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/hooks.md
Demonstrates direct access to the Redux store using `useStore`. This is not recommended for real applications as it bypasses automatic re-renders. Prefer using thunks for side effects.
```javascript
import React from 'react'
import { useStore } from 'react-redux'
export const ExampleComponent = ({ value }) => {
const store = useStore()
const onClick = () => {
// Not _recommended_, but safe
// This avoids subscribing to the state via `useSelector`
// Prefer moving this logic into a thunk instead
const numTodos = store.getState().todos.length
}
// EXAMPLE ONLY! Do not do this in a real app.
// The component will not automatically update if the store state changes
return
{store.getState().todos.length}
}
```
--------------------------------
### Configure Blog Link in siteConfig.js
Source: https://github.com/reduxjs/react-redux/blob/master/website/README.md
Ensure that blog links are enabled and labeled in the `headerLinks` array within `website/siteConfig.js` if you are adding blog posts.
```javascript
headerLinks: [
...
{ blog: true, label: 'Blog' },
...
]
```
--------------------------------
### Use Redux Hooks in React Components
Source: https://github.com/reduxjs/react-redux/blob/master/docs/introduction/getting-started.md
Utilize `useSelector` to read state from the Redux store and `useDispatch` to dispatch actions. This example shows a counter component interacting with `counterSlice`.
```jsx
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {
decrement,
increment,
incrementByAmount,
incrementAsync,
selectCount,
} from './counterSlice'
import styles from './Counter.module.css'
export function Counter() {
const count = useSelector(selectCount)
const dispatch = useDispatch()
return (
)
}
```
--------------------------------
### Run Project Tests
Source: https://github.com/reduxjs/react-redux/blob/master/CONTRIBUTING.md
Execute all project tests to ensure code quality and functionality. This command runs the test suite defined in the project.
```bash
yarn test
```
--------------------------------
### Get Todos By Visibility Filter Selector
Source: https://github.com/reduxjs/react-redux/blob/master/docs/tutorials/connect.md
A selector function that filters the list of todos based on the current visibility filter ('all', 'completed', 'incomplete') stored in the Redux state.
```javascript
export const getTodosByVisibilityFilter = state => {
const todos = getTodos(state);
const filter = state.visibilityFilters;
switch (filter) {
case 'all':
return todos;
case 'completed':
return todos.filter(todo => todo.completed);
case 'incomplete':
return todos.filter(todo => !todo.completed);
default:
throw new Error('Unknown filter: ' + filter);
}
};
```
--------------------------------
### Options Object for connect
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
An object to configure advanced options for the `connect` function, such as context, equality checks, and ref forwarding.
```javascript
{
context?: Object,
areStatesEqual?: Function,
areOwnPropsEqual?: Function,
areStatePropsEqual?: Function,
areMergedPropsEqual?: Function,
forwardRef?: boolean,
}
```
--------------------------------
### Object Shorthand for mapDispatchToProps
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
Demonstrates the recommended object shorthand for mapDispatchToProps, where connect automatically calls bindActionCreators internally.
```javascript
// React Redux does this for you automatically:
;(dispatch) => bindActionCreators(mapDispatchToProps, dispatch)
```
```javascript
const mapDispatchToProps = {
increment,
decrement,
reset,
}
```
```javascript
import { increment, decrement, reset } from './counterActions'
const actionCreators = {
increment,
decrement,
reset,
}
export default connect(mapState, actionCreators)(Counter)
// or
export default connect(mapState, { increment, decrement, reset })(Counter)
```
--------------------------------
### Basic connect function usage
Source: https://github.com/reduxjs/react-redux/blob/master/docs/tutorials/connect.md
Demonstrates the standard way to use the `connect` function with `mapStateToProps` and `mapDispatchToProps`. The `connect` function returns a higher-order component that wraps your React component.
```javascript
const mapStateToProps = (state, ownProps) => ({
// ... computed data from state and optionally ownProps
})
const mapDispatchToProps = {
// ... normally is an object full of action creators
}
// `connect` returns a new function that accepts the component to wrap:
const connectToStore = connect(mapStateToProps, mapDispatchToProps)
// and that function returns the connected, wrapper component:
const ConnectedComponent = connectToStore(Component)
// We normally do both in one step, like this:
connect(mapStateToProps, mapDispatchToProps)(Component)
```
--------------------------------
### createStoreHook
Source: https://github.com/reduxjs/react-redux/blob/master/etc/react-redux.dt-types.api.md
The `createStoreHook` function generates a custom hook for accessing the Redux store instance from a specific context. This hook allows functional components to directly interact with the store, such as getting the current state or subscribing to changes.
```typescript
export function createStoreHook(context?: Context>): () => Store
```
--------------------------------
### Advanced mapDispatchToProps Usage with bindActionCreators
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
Demonstrates dispatching actions using both plain objects and action creators, and how `bindActionCreators` can be used. The `dispatch` function itself can also be returned.
```javascript
const createMyAction = () => ({ type: 'MY_ACTION' })
const mapDispatchToProps = (dispatch, ownProps) => {
const boundActions = bindActionCreators({ createMyAction }, dispatch)
return {
dispatchPlainObject: () => dispatch({ type: 'MY_ACTION' }),
dispatchActionCreatedByActionCreator: () => dispatch(createMyAction()),
...boundActions,
// you may return dispatch here
dispatch,
}
}
```
--------------------------------
### Batching multiple dispatches with batch()
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/batch.md
Use `batch()` to ensure multiple actions dispatched outside of React event handlers result in a single re-render. This example shows dispatching two `increment` actions within a `batch` call.
```typescript
import { batch } from 'react-redux'
function myThunk() {
return (dispatch, getState) => {
// should only result in one combined re-render, not two
batch(() => {
dispatch(increment())
dispatch(increment())
})
}
}
```
--------------------------------
### connect() Function Signature
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
The connect function signature, accepting optional mapStateToProps, mapDispatchToProps, mergeProps, and options.
```javascript
function connect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?)
```
--------------------------------
### Connect Component with Default Dispatch
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
Use `connect()` without a second argument to provide `dispatch` as a prop to your component. This is useful when you need direct access to dispatch actions.
```javascript
connect()(MyComponent)
// which is equivalent with
connect(null, null)(MyComponent)
// or
connect(mapStateToProps /** no second argument */)(MyComponent)
```
--------------------------------
### Build React Redux Project
Source: https://github.com/reduxjs/react-redux/blob/master/CONTRIBUTING.md
Run the build task to generate both CommonJS and UMD builds of the project. This command compiles the source code into distributable formats.
```bash
yarn build
```
--------------------------------
### Add New Docs Page to Sidebar
Source: https://github.com/reduxjs/react-redux/blob/master/website/README.md
Create a new markdown file in the `docs/` directory and reference its ID in `website/sidebar.json` to include it in a sidebar category.
```md
---
id: newly-created-doc
title: This Doc Needs To Be Edited
---
My new content here..
```
--------------------------------
### Define Root State and Dispatch Types
Source: https://github.com/reduxjs/react-redux/blob/master/docs/tutorials/typescript.md
Infer `RootState` and `AppDispatch` types from the store configuration for correct type checking. This ensures types update automatically as the store evolves.
```typescript
import {
configureStore,
} from '@reduxjs/toolkit'
// ...
const store = configureStore({
reducer: {
posts: postsReducer,
comments: commentsReducer,
users: usersReducer,
},
})
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
```
--------------------------------
### Connect Component Without Store Subscription
Source: https://github.com/reduxjs/react-redux/blob/master/docs/tutorials/connect.md
Use `connect()` without arguments when a component does not need to re-render based on store changes but still requires access to the `dispatch` function via props.
```javascript
// ... Component
export default connect()(Component) // Component will receive `dispatch` (just like our !)
```
--------------------------------
### Inject All Action Creators
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
Injects all action creators from a module without subscribing to the store. Ensure the action creators are imported correctly.
```javascript
import * as actionCreators from './actionCreators'
export default connect(null, actionCreators)(TodoApp)
```
--------------------------------
### Binding Action Creators with bindActionCreators
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
Demonstrates how to use bindActionCreators to bind individual action creators or an object of action creators to the dispatch function.
```javascript
import { bindActionCreators } from 'redux'
const increment = () => ({ type: 'INCREMENT' })
const decrement = () => ({ type: 'DECREMENT' })
const reset = () => ({ type: 'RESET' })
// binding an action creator
// returns (...args) => dispatch(increment(...args))
const boundIncrement = bindActionCreators(increment, dispatch)
// binding an object full of action creators
const boundActionCreators = bindActionCreators(
{ increment, decrement, reset },
dispatch,
)
// returns
// {
// increment: (...args) => dispatch(increment(...args)),
// decrement: (...args) => dispatch(decrement(...args)),
// reset: (...args) => dispatch(reset(...args)),
// }
```
--------------------------------
### Inject Specific State and Multiple Action Creators (Shorthand)
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
Injects a specific state slice ('todos') and multiple action creators ('addTodo', 'deleteTodo') using shorthand syntax for `mapDispatchToProps`. Requires `mapStateToProps`.
```javascript
import { addTodo, deleteTodo } from './actionCreators'
function mapStateToProps(state) {
return { todos: state.todos }
}
const mapDispatchToProps = {
addTodo,
deleteTodo,
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
```
--------------------------------
### Build CommonJS Modules Only
Source: https://github.com/reduxjs/react-redux/blob/master/CONTRIBUTING.md
Execute this command to create only a CommonJS module-per-module build, useful for specific build configurations.
```bash
yarn build:lib
```
--------------------------------
### Clone the React Redux Repository
Source: https://github.com/reduxjs/react-redux/blob/master/CONTRIBUTING.md
Use this command to fork and clone the React Redux repository to your local machine for development.
```bash
git clone https://github.com/your-username/react-redux.git
```
--------------------------------
### Forwarding Arguments to Action Creators with mapDispatchToProps
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
Use this to forward arguments to action creators. The function receives `dispatch` as an argument.
```javascript
const mapDispatchToProps = (dispatch) => {
return {
// explicitly forwarding arguments
onClick: (event) => dispatch(trackClick(event)),
// implicitly forwarding arguments
onReceiveImpressions: (...impressions) =>
dispatch(trackImpressions(impressions)),
}
}
```
--------------------------------
### Inject Specific State and All Action Creators
Source: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md
Combines injecting a specific state slice ('todos') with all action creators from a module. Requires both `mapStateToProps` and an action creators import.
```javascript
import * as actionCreators from './actionCreators'
function mapStateToProps(state) {
return { todos: state.todos }
}
export default connect(mapStateToProps, actionCreators)(TodoApp)
```
--------------------------------
### Type Definitions
Source: https://github.com/reduxjs/react-redux/blob/master/etc/react-redux.api.md
Type definitions for state management and action handling.
```APIDOC
## TypedUseSelectorHook
### Description
A generic hook type for `useSelector` that allows for strongly typed state selection.
### Type Definition
```typescript
interface TypedUseSelectorHook {
(selector: (state: TState) => TSelected, equalityFn?: (left: TSelected, right: TSelected) => boolean): TSelected
}
export const useSelector: TypedUseSelectorHook
```
### Usage
Typically used to create a typed version of `useSelector` for your application's root state.
### Example
```typescript
import { TypedUseSelectorHook, useSelector } from 'react-redux'
import { RootState } from './store'
export const useAppSelector: TypedUseSelectorHook = useSelector
// In a component:
const count = useAppSelector(state => state.counter.value)
```
```
```APIDOC
## ResolveThunks
### Description
A utility type that resolves thunk action creators within a props object to their unwrapped function types.
### Type Definition
```typescript
type ResolveThunks = TDispatchProps extends { [key: string]: any } ? { [C in keyof TDispatchProps]: HandleThunkActionCreator } : TDispatchProps
```
### Usage
Useful for typing the `dispatch` prop when using libraries like Redux Thunk, ensuring that thunk action creators are correctly inferred.
### Example
```typescript
import { ThunkAction } from 'redux-thunk'
import { Action } from '@reduxjs/toolkit'
// Define your root state and app dispatch types
interface AppState { /* ... */ }
type AppDispatch = Dispatch | ThunkAction
// Example usage with props
interface MyDispatchProps {
fetchData: () => AppDispatch
}
type ResolvedMyDispatchProps = ResolveThunks
// ResolvedMyDispatchProps will be equivalent to:
// {
// fetchData: () => void
// }
```
```
```APIDOC
## Selector
### Description
A type definition for selector functions used with Redux.
### Type Definition
```typescript
type Selector = TOwnProps extends null | undefined ? (state: S) => TProps : (state: S, ownProps: TOwnProps) => TProps
```
### Usage
Defines the signature for functions that select a portion of the Redux state, optionally accepting component props.
### Example
```typescript
// A simple selector
const selectUserName: Selector = (state) => state.user.name
// A selector that uses ownProps
interface UserProfileProps { userId: string }
const selectUserProfile: Selector = (state, props) => {
return state.users.find(user => user.id === props.userId)
}
```
```
```APIDOC
## SelectorFactory
### Description
A type for functions that create selectors, often used for memoized selectors or selectors requiring dispatch/factory options.
### Type Definition
```typescript
type SelectorFactory = (dispatch: Dispatch, factoryOptions: TFactoryOptions) => Selector
```
### Usage
Used in scenarios where selectors need to be configured or initialized with specific parameters during application setup.
### Example
```typescript
import { createSelector } from 'reselect'
interface MyFactoryOptions { cacheKey: string }
const createMySelector: SelectorFactory = (dispatch, options) => {
return createSelector(
(state: RootState) => state.data,
(data) => {
// Use options.cacheKey or dispatch here if needed
return data.filter(item => item.key === options.cacheKey).length
}
)
}
```
```
```APIDOC
## shallowEqual Utility
### Description
A utility function to perform a shallow comparison between two objects. It checks if the values of own properties are strictly equal.
### Method
`shallowEqual(objA: any, objB: any): boolean`
### Endpoint
N/A (Utility Function)
### Parameters
- **objA** (any) - The first object to compare.
- **objB** (any) - The second object to compare.
### Request Example
```javascript
import { shallowEqual } from 'react-redux'
const obj1 = { a: 1, b: 2 }
const obj2 = { a: 1, b: 2 }
const obj3 = { a: 1, b: 3 }
console.log(shallowEqual(obj1, obj2)) // true
console.log(shallowEqual(obj1, obj3)) // false
```
### Response
- **boolean** - Returns `true` if the objects are shallowly equal, `false` otherwise.
### Response Example
`true` or `false`
```
```APIDOC
## RootStateOrAny
### Description
A type alias that represents either the `DefaultRootState` or `any`, typically used to provide flexibility in state typing.
### Type Definition
```typescript
type RootStateOrAny = AnyIfEmpty
```
### Usage
This type is often used internally or in generic contexts where the exact root state type might not be known or needs to accommodate an empty state scenario.
### Example
```typescript
// Example of how it might be used internally or in a generic context
function processState(state: S) {
// ... logic that works with DefaultRootState or any state
}
```
```
```APIDOC
## Shared Utility Type
### Description
A utility type that helps in defining props where properties from two types (`InjectedProps` and `DecorationTargetProps`) are shared, ensuring type compatibility.
### Type Definition
```typescript
type Shared = {
[P in Extract]?: InjectedProps[P] extends DecorationTargetProps[P] ? DecorationTargetProps[P] : never
}
```
### Usage
Primarily used in higher-order components (HOCs) or decorators to manage prop types, ensuring that props injected by the HOC are compatible with the props expected by the decorated component.
### Example
```typescript
interface InjectedProps { userId: string; theme: 'dark' | 'light' }
interface MyComponentProps { userId: string; data: number }
type CombinedProps = Shared & Omit
// CombinedProps will ensure that 'userId' is compatible, and 'theme' from InjectedProps is optional if not present in MyComponentProps.
```
```
--------------------------------
### Perform Linting with ESLint
Source: https://github.com/reduxjs/react-redux/blob/master/CONTRIBUTING.md
Run the ESLint linter to check for code style violations and potential errors. This command enforces code quality standards across the project.
```bash
yarn lint
```
--------------------------------
### Binding Actions on Component Mount with mapDispatchToProps
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
This pattern binds actions when the component mounts. It uses `dispatch` and does not rely on `ownProps`.
```javascript
const mapDispatchToProps = dispatch => {
return {
toggleTodo: todoId => dispatch(toggleTodo(todoId))
}
}
```
--------------------------------
### Add Slice Reducer to the Store
Source: https://github.com/reduxjs/react-redux/blob/master/docs/tutorials/quick-start.md
Import the generated slice reducer and add it to the store configuration by defining a field within the `reducer` object.
```javascript
import { configureStore } from '@reduxjs/toolkit'
// highlight-next-line
import counterReducer from '../features/counter/counterSlice'
export default configureStore({
reducer: {
// highlight-next-line
counter: counterReducer,
},
})
```
--------------------------------
### Matching Props Utility
Source: https://github.com/reduxjs/react-redux/blob/master/etc/react-redux.api.md
A utility type for defining how injected props should match decoration target props.
```APIDOC
## Matching
### Description
The `Matching` utility type is used to ensure that injected props are compatible with the props of the component being decorated. It allows for partial matching and type checking.
### Type
`Matching`
- `InjectedProps`: The type of props injected by a higher-order component or hook.
- `DecorationTargetProps`: The type of props expected by the component being decorated.
### Usage
Helps in defining the props signature for higher-order components to ensure type safety when passing props down.
```
--------------------------------
### Provide Redux Store to React Application
Source: https://github.com/reduxjs/react-redux/blob/master/docs/tutorials/quick-start.md
Make the Redux store available to your React components by wrapping your application with the Redux Provider component in index.js.
```javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import App from './App'
// highlight-start
import store from './app/store'
import { Provider } from 'react-redux'
// highlight-end
// As of React 18
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
// highlight-next-line
,
)
```
--------------------------------
### Utility Types
Source: https://github.com/reduxjs/react-redux/blob/master/etc/react-redux.dt-types.api.md
Provides utility types for defining selectors and handling dispatch props.
```APIDOC
## Utility Types
### Selector Type
`type Selector = TOwnProps extends | null | undefined ? (state: S) => TProps : (state: S, ownProps: TOwnProps) => TProps`
### Selector Factory Type
`type SelectorFactory = (dispatch: Dispatch, factoryOptions: TFactoryOptions) => Selector`
### TypedUseSelectorHook Type
`interface TypedUseSelectorHook { (selector: (state: TState) => TSelected, equalityFn?: (left: TSelected, right: TSelected) => boolean): TSelected }`
### ResolveThunks Type
`type ResolveThunks = TDispatchProps extends { [key: string]: any } ? { [C in keyof TDispatchProps]: HandleThunkActionCreator } : TDispatchProps`
### shallowEqual Function
`function shallowEqual(left: T, right: any): boolean`
### Shared Type
`type Shared = { [P in Extract]?: InjectedProps[P] extends DecorationTargetProps[P] ? DecorationTargetProps[P] : never }`
```
--------------------------------
### Using bindActionCreators in mapDispatchToProps
Source: https://github.com/reduxjs/react-redux/blob/master/docs/using-react-redux/connect-dispatching-actions-with-mapDispatchToProps.md
Shows how to integrate bindActionCreators within the mapDispatchToProps function to automatically bind action creators.
```javascript
import { bindActionCreators } from 'redux'
// ...
function mapDispatchToProps(dispatch) {
return bindActionCreators({ increment, decrement, reset }, dispatch)
}
// component receives props.increment, props.decrement, props.reset
connect(null, mapDispatchToProps)(Counter)
```