- vừa được xem lúc

[React] Cùng tìm hiểu về Redux Toolkit, một phiên bản mới của Redux

0 0 27

Người đăng: Le Ba Thanh Tuan

Theo Viblo Asia

1. Redux Toolkit (RTK) là gì và tại sao lại có nó?

npm install @reduxjs/toolkit
  • RTK là một thư viện giúp mình viết Redux tốt hơn, dễ hơn và đơn giản hơn. (tiêu chuẩn để viết Redux)
  • Ba vấn đề làm nền tảng ra đời RTK:
- Configuring a Redux store is too complicated.
- I have to add a lot of packages to get Redux to do anything useful.
- Redux requires too much boilerplate code.

2. RTK bao gồm những gì?

configureStore()

  • Có sẵn Redux DevTools
  • Có sẵn redux-thunk để thực hiện async actions
// Khi chưa có Redux Toolkit
// store.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers';
// Enable to use redux dev tool in development mode
const composeEnhancers = 'development' === process.env.NODE_ENV ? (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose) : compose;
// Use redux-thunk as a redux middleware
const enhancer = composeEnhancers(applyMiddleware(thunkMiddleware));
const store = createStore(rootReducer, {}, enhancer);
export default store;
// Khi đã có redux toolkit 🤣
// store.js
import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './reducers'
const store = configureStore({ reducer: rootReducer })

createReducer()

// Không có Redux Toolkit
function counterReducer(state = 0, action) { switch (action.type) { case 'increment': return state + action.payload case 'decrement': return state - action.payload default: return state }
}
// Có Redux Toolkit
// - Mỗi key là một case
// - Không cần handle default case
const counterReducer = createReducer(0, { increment: (state, action) => state + action.payload, decrement: (state, action) => state - action.payload
})
// Một điểm hay nữa là reducer có thể mutate data trực tiếp.
// Bản chất bên dưới họ sử dụng thư viện Immerjs
const todoReducer = createReducer([], { addTodo: (state, action) => { // 1. Có thể mutate data trực tiếp 🎉 state.push(action.payload) }, removeTodo: (state, action) => { // 2. Hoặc phải trả về state mới // CHỨ KO ĐƯỢC cả 1 và 2 nha 😎 const newState = [...state]; newState.splice(action.payload, 1); return newState; }
})

createAction()

// Không có redux toolkit
const INCREMENT = 'counter/increment'
function increment(amount) { return { type: INCREMENT, payload: amount }
}
const action = increment(3)
// { type: 'counter/increment', payload: 3 }
// Có redux toolkit
const increment = createAction('counter/increment')
const action = increment(3)
// returns { type: 'counter/increment', payload: 3 }
console.log(increment.toString())
// 'counter/increment'

Các bạn đọc thêm những hàm sau nữa nhé 😉

3. Setup một ví dụ đơn giản sử dụng RTK

// 1. Setup todo slice
// todoSlice.js
const todoSlice = createSlice({ name: 'todos', initialState: [], reducers: { addPost(state, action) { state.push(action.payload); }, removePost(state, action) { state.splice(action.payload, 1) } }
});
const { actions, reducer } = todoSlice;
export const { addPost, removePost } = actions;
export default reducer;
// 2. Setup redux store
// store.js
import { configureStore } from '@reduxjs/toolkit';
import todoSlice from 'features/todos/todoSlice';
const store = configureStore({ reducer: { todos: todoSlice },
})
// 3. Bind Redux Provider to App
// src/index.js
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
function Main() { return ( <Provider store={store}> <App /> </Provider> )
}
// 4. Using redux in component
// todo.jsx
import { useDispatch, useSelector } from 'react-redux';
import { removeTodo } from 'features/todos/todoSlice';
function Todo() { const dispatch = useDispatch(); const todoList = useSelector(state => state.todos); const handleTodoClick = (todo, idx) => { const action = removeTodo(idx); dispatch(action); } return ( <ul> {todoList.map((todo, idx) => ( <li key={todo.id} onClick={() => handleTodoClick(todo, idx)}> {todo.title} </li> ))} </ul> )
}

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Cài đặt WSL / WSL2 trên Windows 10 để code như trên Ubuntu

Sau vài ba năm mình chuyển qua code trên Ubuntu thì thật không thể phủ nhận rằng mình đã yêu em nó. Cá nhân mình sử dụng Ubuntu để code web thì thật là tuyệt vời.

0 0 374

- vừa được xem lúc

Đặt tên commit message sao cho "tình nghĩa anh em chắc chắn bền lâu"????

. Lời mở đầu. .

1 1 701

- vừa được xem lúc

Tìm hiểu về Resource Controller trong Laravel

Giới thiệu. Trong laravel, việc sử dụng các route post, get, group để gọi đến 1 action của Controller đã là quá quen đối với các bạn sử dụng framework này.

0 0 335

- vừa được xem lúc

Phân quyền đơn giản với package Laravel permission

Như các bạn đã biết, phân quyền trong một ứng dụng là một phần không thể thiếu trong việc phát triển phần mềm, dù đó là ứng dụng web hay là mobile. Vậy nên, hôm nay mình sẽ giới thiệu một package có thể giúp các bạn phân quyền nhanh và đơn giản trong một website được viết bằng PHP với framework là L

0 0 421

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414