|
1 | 1 | # Redux Quick Reference |
2 | 2 |
|
| 3 | +<br/> |
| 4 | + |
3 | 5 | ## Creating a store |
4 | 6 |
|
5 | 7 | A store is made from a reducer function, which takes the current state, and returns a new state depending on the action it was given. |
@@ -157,3 +159,238 @@ const store = createStore(reducer, {}, enhancer) |
157 | 159 | <div align="right"> |
158 | 160 | <b><a href="#">↥ back to top</a></b> |
159 | 161 | </div> |
| 162 | + |
| 163 | +## Action creators |
| 164 | + |
| 165 | +Action creators are functions that return action objects. |
| 166 | + |
| 167 | +```js |
| 168 | +// Action type constants |
| 169 | +const INCREMENT = 'INCREMENT' |
| 170 | +const DECREMENT = 'DECREMENT' |
| 171 | + |
| 172 | +// Action creators |
| 173 | +const increment = () => ({ type: INCREMENT }) |
| 174 | +const decrement = () => ({ type: DECREMENT }) |
| 175 | +const incrementBy = (amount) => ({ type: 'INCREMENT_BY', payload: amount }) |
| 176 | + |
| 177 | +// Dispatching via action creators |
| 178 | +store.dispatch(increment()) |
| 179 | +store.dispatch(incrementBy(5)) |
| 180 | +``` |
| 181 | + |
| 182 | +<div align="right"> |
| 183 | + <b><a href="#">↥ back to top</a></b> |
| 184 | +</div> |
| 185 | + |
| 186 | +## Thunks (async actions) |
| 187 | + |
| 188 | +Thunks let you dispatch functions instead of plain objects for async logic. |
| 189 | + |
| 190 | +```js |
| 191 | +import { createStore, applyMiddleware } from 'redux' |
| 192 | +import thunk from 'redux-thunk' |
| 193 | + |
| 194 | +const store = createStore(reducer, applyMiddleware(thunk)) |
| 195 | + |
| 196 | +// A thunk action creator |
| 197 | +function fetchUser(id) { |
| 198 | + return async (dispatch) => { |
| 199 | + dispatch({ type: 'FETCH_USER_REQUEST' }) |
| 200 | + try { |
| 201 | + const res = await fetch(`/api/users/${id}`) |
| 202 | + const data = await res.json() |
| 203 | + dispatch({ type: 'FETCH_USER_SUCCESS', payload: data }) |
| 204 | + } catch (err) { |
| 205 | + dispatch({ type: 'FETCH_USER_FAILURE', error: err.message }) |
| 206 | + } |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +store.dispatch(fetchUser(1)) |
| 211 | +``` |
| 212 | + |
| 213 | +<div align="right"> |
| 214 | + <b><a href="#">↥ back to top</a></b> |
| 215 | +</div> |
| 216 | + |
| 217 | +## React Hooks |
| 218 | + |
| 219 | +`useSelector` reads from the store; `useDispatch` returns the dispatch function. |
| 220 | + |
| 221 | +```js |
| 222 | +import { useSelector, useDispatch } from 'react-redux' |
| 223 | + |
| 224 | +function Counter() { |
| 225 | + const count = useSelector((state) => state.counter.value) |
| 226 | + const dispatch = useDispatch() |
| 227 | + |
| 228 | + return ( |
| 229 | + <div> |
| 230 | + <span>{count}</span> |
| 231 | + <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button> |
| 232 | + <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button> |
| 233 | + </div> |
| 234 | + ) |
| 235 | +} |
| 236 | +``` |
| 237 | + |
| 238 | +<div align="right"> |
| 239 | + <b><a href="#">↥ back to top</a></b> |
| 240 | +</div> |
| 241 | + |
| 242 | +## Redux Toolkit – configureStore |
| 243 | + |
| 244 | +`configureStore` wraps `createStore` with good defaults (DevTools, thunk middleware). |
| 245 | + |
| 246 | +```js |
| 247 | +import { configureStore } from '@reduxjs/toolkit' |
| 248 | +import counterReducer from './counterSlice' |
| 249 | + |
| 250 | +const store = configureStore({ |
| 251 | + reducer: { |
| 252 | + counter: counterReducer, |
| 253 | + }, |
| 254 | +}) |
| 255 | + |
| 256 | +export default store |
| 257 | +``` |
| 258 | + |
| 259 | +<div align="right"> |
| 260 | + <b><a href="#">↥ back to top</a></b> |
| 261 | +</div> |
| 262 | + |
| 263 | +## Redux Toolkit – createSlice |
| 264 | + |
| 265 | +`createSlice` generates action creators and action types automatically. |
| 266 | + |
| 267 | +```js |
| 268 | +import { createSlice } from '@reduxjs/toolkit' |
| 269 | + |
| 270 | +const counterSlice = createSlice({ |
| 271 | + name: 'counter', |
| 272 | + initialState: { value: 0 }, |
| 273 | + reducers: { |
| 274 | + increment(state) { |
| 275 | + state.value += 1 // Immer allows direct mutation |
| 276 | + }, |
| 277 | + decrement(state) { |
| 278 | + state.value -= 1 |
| 279 | + }, |
| 280 | + incrementByAmount(state, action) { |
| 281 | + state.value += action.payload |
| 282 | + }, |
| 283 | + }, |
| 284 | +}) |
| 285 | + |
| 286 | +export const { increment, decrement, incrementByAmount } = counterSlice.actions |
| 287 | +export default counterSlice.reducer |
| 288 | +``` |
| 289 | + |
| 290 | +<div align="right"> |
| 291 | + <b><a href="#">↥ back to top</a></b> |
| 292 | +</div> |
| 293 | + |
| 294 | +## Redux Toolkit – createAsyncThunk |
| 295 | + |
| 296 | +Handles async lifecycles (`pending`, `fulfilled`, `rejected`) automatically. |
| 297 | + |
| 298 | +```js |
| 299 | +import { createAsyncThunk, createSlice } from '@reduxjs/toolkit' |
| 300 | + |
| 301 | +export const fetchUser = createAsyncThunk('users/fetchById', async (userId) => { |
| 302 | + const res = await fetch(`/api/users/${userId}`) |
| 303 | + return res.json() |
| 304 | +}) |
| 305 | + |
| 306 | +const usersSlice = createSlice({ |
| 307 | + name: 'users', |
| 308 | + initialState: { data: null, status: 'idle', error: null }, |
| 309 | + reducers: {}, |
| 310 | + extraReducers: (builder) => { |
| 311 | + builder |
| 312 | + .addCase(fetchUser.pending, (state) => { state.status = 'loading' }) |
| 313 | + .addCase(fetchUser.fulfilled, (state, action) => { |
| 314 | + state.status = 'succeeded' |
| 315 | + state.data = action.payload |
| 316 | + }) |
| 317 | + .addCase(fetchUser.rejected, (state, action) => { |
| 318 | + state.status = 'failed' |
| 319 | + state.error = action.error.message |
| 320 | + }) |
| 321 | + }, |
| 322 | +}) |
| 323 | + |
| 324 | +export default usersSlice.reducer |
| 325 | +``` |
| 326 | + |
| 327 | +<div align="right"> |
| 328 | + <b><a href="#">↥ back to top</a></b> |
| 329 | +</div> |
| 330 | + |
| 331 | +## Selectors |
| 332 | + |
| 333 | +Selectors are functions that extract and derive data from state. |
| 334 | + |
| 335 | +```js |
| 336 | +// Basic selector |
| 337 | +const selectCount = (state) => state.counter.value |
| 338 | + |
| 339 | +// Derived selector |
| 340 | +const selectDoubleCount = (state) => state.counter.value * 2 |
| 341 | + |
| 342 | +// Usage with useSelector |
| 343 | +const count = useSelector(selectCount) |
| 344 | +``` |
| 345 | + |
| 346 | +<div align="right"> |
| 347 | + <b><a href="#">↥ back to top</a></b> |
| 348 | +</div> |
| 349 | + |
| 350 | +## Memoized selectors with Reselect |
| 351 | + |
| 352 | +`createSelector` memoizes expensive derived state computations. |
| 353 | + |
| 354 | +```js |
| 355 | +import { createSelector } from 'reselect' // or '@reduxjs/toolkit' |
| 356 | + |
| 357 | +const selectItems = (state) => state.cart.items |
| 358 | +const selectTax = (state) => state.cart.taxRate |
| 359 | + |
| 360 | +const selectTotal = createSelector( |
| 361 | + [selectItems, selectTax], |
| 362 | + (items, taxRate) => { |
| 363 | + const subtotal = items.reduce((sum, item) => sum + item.price, 0) |
| 364 | + return subtotal * (1 + taxRate) |
| 365 | + } |
| 366 | +) |
| 367 | + |
| 368 | +// Only recomputes when `items` or `taxRate` change |
| 369 | +const total = useSelector(selectTotal) |
| 370 | +``` |
| 371 | + |
| 372 | +<div align="right"> |
| 373 | + <b><a href="#">↥ back to top</a></b> |
| 374 | +</div> |
| 375 | + |
| 376 | +## Redux DevTools |
| 377 | + |
| 378 | +Enable browser DevTools support (built into `configureStore` by default). |
| 379 | + |
| 380 | +```js |
| 381 | +import { createStore } from 'redux' |
| 382 | + |
| 383 | +// Legacy createStore – enable DevTools manually |
| 384 | +const store = createStore( |
| 385 | + reducer, |
| 386 | + window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() |
| 387 | +) |
| 388 | + |
| 389 | +// Redux Toolkit – DevTools are enabled automatically |
| 390 | +import { configureStore } from '@reduxjs/toolkit' |
| 391 | +const store = configureStore({ reducer }) |
| 392 | +``` |
| 393 | + |
| 394 | +<div align="right"> |
| 395 | + <b><a href="#">↥ back to top</a></b> |
| 396 | +</div> |
0 commit comments