|
| 1 | +--- |
| 2 | +id: quick-start |
| 3 | +title: Quick Start |
| 4 | +sidebar_label: Quick Start |
| 5 | +hide_title: true |
| 6 | +--- |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +# React Redux Quick Start |
| 11 | + |
| 12 | +:::tip What You'll Learn |
| 13 | + |
| 14 | +- How to set up and use Redux Toolkit with React Redux |
| 15 | + |
| 16 | +::: |
| 17 | + |
| 18 | +:::info Prerequisites |
| 19 | + |
| 20 | +- Familiarity with [ES6 syntax and features](https://www.taniarascia.com/es6-syntax-and-feature-overview/) |
| 21 | +- Knowledge of React terminology: [JSX](https://react.dev/learn/writing-markup-with-jsx), [State](https://react.dev/learn/state-a-components-memory), [Function Components, Props](https://react.dev/learn/passing-props-to-a-component), and [Hooks](https://react.dev/reference/react#) |
| 22 | +- Understanding of [Redux terms and concepts](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow) |
| 23 | + |
| 24 | +::: |
| 25 | + |
| 26 | +## Introduction |
| 27 | + |
| 28 | +Welcome to the React Redux Quick Start tutorial! **This tutorial will briefly introduce you to React Redux and teach you how to start using it correctly**. |
| 29 | + |
| 30 | +### How to Read This Tutorial |
| 31 | + |
| 32 | +This page will focus on just how to set up a Redux application with Redux Toolkit and the main APIs you'll use. For explanations of what Redux is, how it works, and full examples of how to use Redux Toolkit, see [the Redux core docs tutorials](https://redux.js.org/tutorials/index). |
| 33 | + |
| 34 | +For this tutorial, we assume that you're using Redux Toolkit and React Redux together, as that is the standard Redux usage pattern. The examples are based on [a typical Create-React-App folder structure](https://create-react-app.dev/docs/folder-structure) where all the application code is in a `src`, but the patterns can be adapted to whatever project or folder setup you're using. |
| 35 | + |
| 36 | +The [Redux+JS template for Create-React-App](https://github.com/reduxjs/cra-template-redux) comes with this same project setup already configured. |
| 37 | + |
| 38 | +## Usage Summary |
| 39 | + |
| 40 | +### Install Redux Toolkit and React Redux |
| 41 | + |
| 42 | +Add the Redux Toolkit and React Redux packages to your project: |
| 43 | + |
| 44 | +```sh |
| 45 | +npm install @reduxjs/toolkit react-redux |
| 46 | +``` |
| 47 | + |
| 48 | +### Create a Redux Store |
| 49 | + |
| 50 | +Create a file named `src/app/store.js`. Import the `configureStore` API from Redux Toolkit. We'll start by creating an empty Redux store, and exporting it: |
| 51 | + |
| 52 | +```js title="app/store.js" |
| 53 | +import { configureStore } from '@reduxjs/toolkit' |
| 54 | + |
| 55 | +export default configureStore({ |
| 56 | + reducer: {}, |
| 57 | +}) |
| 58 | +``` |
| 59 | + |
| 60 | +This creates a Redux store, and also automatically configure the Redux DevTools extension so that you can inspect the store while developing. |
| 61 | + |
| 62 | +### Provide the Redux Store to React |
| 63 | + |
| 64 | +Once the store is created, we can make it available to our React components by putting a React Redux `<Provider>` around our application in `src/index.js`. Import the Redux store we just created, put a `<Provider>` around your `<App>`, and pass the store as a prop: |
| 65 | + |
| 66 | +```js title="index.js" |
| 67 | +import React from 'react' |
| 68 | +import ReactDOM from 'react-dom/client' |
| 69 | +import './index.css' |
| 70 | +import App from './App' |
| 71 | +// highlight-start |
| 72 | +import store from './app/store' |
| 73 | +import { Provider } from 'react-redux' |
| 74 | +// highlight-end |
| 75 | + |
| 76 | +// As of React 18 |
| 77 | +const root = ReactDOM.createRoot(document.getElementById('root')) |
| 78 | + |
| 79 | +root.render( |
| 80 | + // highlight-next-line |
| 81 | + <Provider store={store}> |
| 82 | + <App /> |
| 83 | + </Provider>, |
| 84 | +) |
| 85 | +``` |
| 86 | + |
| 87 | +### Create a Redux State Slice |
| 88 | + |
| 89 | +Add a new file named `src/features/counter/counterSlice.js`. In that file, import the `createSlice` API from Redux Toolkit. |
| 90 | + |
| 91 | +Creating a slice requires a string name to identify the slice, an initial state value, and one or more reducer functions to define how the state can be updated. Once a slice is created, we can export the generated Redux action creators and the reducer function for the whole slice. |
| 92 | + |
| 93 | +Redux requires that [we write all state updates immutably, by making copies of data and updating the copies](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow#immutability). However, Redux Toolkit's `createSlice` and `createReducer` APIs use [Immer](https://immerjs.github.io/immer/) inside to allow us to [write "mutating" update logic that becomes correct immutable updates](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux#immutable-updates-with-immer). |
| 94 | + |
| 95 | +```js title="features/counter/counterSlice.js" |
| 96 | +import { createSlice } from '@reduxjs/toolkit' |
| 97 | + |
| 98 | +export const counterSlice = createSlice({ |
| 99 | + name: 'counter', |
| 100 | + initialState: { |
| 101 | + value: 0, |
| 102 | + }, |
| 103 | + reducers: { |
| 104 | + increment: (state) => { |
| 105 | + // Redux Toolkit allows us to write "mutating" logic in reducers. It |
| 106 | + // doesn't actually mutate the state because it uses the Immer library, |
| 107 | + // which detects changes to a "draft state" and produces a brand new |
| 108 | + // immutable state based off those changes. |
| 109 | + // Also, no return statement is required from these functions. |
| 110 | + state.value += 1 |
| 111 | + }, |
| 112 | + decrement: (state) => { |
| 113 | + state.value -= 1 |
| 114 | + }, |
| 115 | + incrementByAmount: (state, action) => { |
| 116 | + state.value += action.payload |
| 117 | + }, |
| 118 | + }, |
| 119 | +}) |
| 120 | + |
| 121 | +// Action creators are generated for each case reducer function |
| 122 | +export const { increment, decrement, incrementByAmount } = counterSlice.actions |
| 123 | + |
| 124 | +export default counterSlice.reducer |
| 125 | +``` |
| 126 | + |
| 127 | +### Add Slice Reducers to the Store |
| 128 | + |
| 129 | +Next, we need to import the reducer function from the counter slice and add it to our store. By defining a field inside the `reducer` parameter, we tell the store to use this slice reducer function to handle all updates to that state. |
| 130 | + |
| 131 | +```js title="app/store.js" |
| 132 | +import { configureStore } from '@reduxjs/toolkit' |
| 133 | +// highlight-next-line |
| 134 | +import counterReducer from '../features/counter/counterSlice' |
| 135 | + |
| 136 | +export default configureStore({ |
| 137 | + reducer: { |
| 138 | + // highlight-next-line |
| 139 | + counter: counterReducer, |
| 140 | + }, |
| 141 | +}) |
| 142 | +``` |
| 143 | + |
| 144 | +### Use Redux State and Actions in React Components |
| 145 | + |
| 146 | +Now we can use the React Redux hooks to let React components interact with the Redux store. We can read data from the store with `useSelector`, and dispatch actions using `useDispatch`. Create a `src/features/counter/Counter.js` file with a `<Counter>` component inside, then import that component into `App.js` and render it inside of `<App>`. |
| 147 | + |
| 148 | +```jsx title="features/counter/Counter.js" |
| 149 | +import React from 'react' |
| 150 | +import { useSelector, useDispatch } from 'react-redux' |
| 151 | +import { decrement, increment } from './counterSlice' |
| 152 | +import styles from './Counter.module.css' |
| 153 | + |
| 154 | +export function Counter() { |
| 155 | + const count = useSelector((state) => state.counter.value) |
| 156 | + const dispatch = useDispatch() |
| 157 | + |
| 158 | + return ( |
| 159 | + <div> |
| 160 | + <div> |
| 161 | + <button |
| 162 | + aria-label="Increment value" |
| 163 | + onClick={() => dispatch(increment())} |
| 164 | + > |
| 165 | + Increment |
| 166 | + </button> |
| 167 | + <span>{count}</span> |
| 168 | + <button |
| 169 | + aria-label="Decrement value" |
| 170 | + onClick={() => dispatch(decrement())} |
| 171 | + > |
| 172 | + Decrement |
| 173 | + </button> |
| 174 | + </div> |
| 175 | + </div> |
| 176 | + ) |
| 177 | +} |
| 178 | +``` |
| 179 | + |
| 180 | +Now, any time you click the "Increment" and "Decrement buttons: |
| 181 | + |
| 182 | +- The corresponding Redux action will be dispatched to the store |
| 183 | +- The counter slice reducer will see the actions and update its state |
| 184 | +- The `<Counter>` component will see the new state value from the store and re-render itself with the new data |
| 185 | + |
| 186 | +## What You've Learned |
| 187 | + |
| 188 | +That was a brief overview of how to set up and use Redux Toolkit with React. Recapping the details: |
| 189 | + |
| 190 | +:::tip Summary |
| 191 | + |
| 192 | +- **Create a Redux store with `configureStore`** |
| 193 | + - `configureStore` accepts a `reducer` function as a named argument |
| 194 | + - `configureStore` automatically sets up the store with good default settings |
| 195 | +- **Provide the Redux store to the React application components** |
| 196 | + - Put a React Redux `<Provider>` component around your `<App />` |
| 197 | + - Pass the Redux store as `<Provider store={store}>` |
| 198 | +- **Create a Redux "slice" reducer with `createSlice`** |
| 199 | + - Call `createSlice` with a string name, an initial state, and named reducer functions |
| 200 | + - Reducer functions may "mutate" the state using Immer |
| 201 | + - Export the generated slice reducer and action creators |
| 202 | +- **Use the React Redux `useSelector/useDispatch` hooks in React components** |
| 203 | + - Read data from the store with the `useSelector` hook |
| 204 | + - Get the `dispatch` function with the `useDispatch` hook, and dispatch actions as needed |
| 205 | + |
| 206 | +::: |
| 207 | + |
| 208 | +### Full Counter App Example |
| 209 | + |
| 210 | +Here's the complete Counter application as a running CodeSandbox: |
| 211 | + |
| 212 | +<iframe |
| 213 | + class="codesandbox" |
| 214 | + src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-counter-example/tree/master/?fontsize=14&hidenavigation=1&module=%2Fsrc%2Ffeatures%2Fcounter%2FcounterSlice.js&theme=dark&runonclick=1" |
| 215 | + title="redux-essentials-example" |
| 216 | + allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb" |
| 217 | + sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin" |
| 218 | +></iframe> |
| 219 | +
|
| 220 | +## What's Next? |
| 221 | + |
| 222 | +We recommend going through [**the "Redux Essentials" and "Redux Fundamentals" tutorials in the Redux core docs**](https://redux.js.org/tutorials/index), which will give you a complete understanding of how Redux works, what Redux Toolkit and React Redux do, and how to use it correctly. |
0 commit comments