Translate

Views

Saturday, February 15, 2025

Redux React (Cách nâng cao để truyền props trong react)

 Đừng lo lắng, mình sẽ giúp bạn từng bước để hiểu và sử dụng Redux Toolkit trong React, ngay cả khi bạn chưa có kinh nghiệm trước đó!

https://chatgpt.com/share/67b0bbf3-9b74-8007-a939-0db2039c78f3

Bước 1: Cài đặt Redux Toolkit và React-Redux

Trước tiên, bạn cần cài đặt Redux Toolkit và React-Redux trong dự án React của bạn.

Mở terminal và chạy lệnh sau:

bash
pnpm add @reduxjs/toolkit react-redux

Bước 2: Tạo Store với Redux Toolkit

Trong thư mục src, tạo một thư mục mới tên là store. Trong thư mục đó, tạo một file store.js.

js
// src/store/store.js import { configureStore } from '@reduxjs/toolkit'; // Tạo một reducer cơ bản (có thể sau này bạn sẽ thêm nhiều reducers khác) const initialState = { count: 0 }; const counterReducer = (state = initialState, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; // Cấu hình store với Redux Toolkit const store = configureStore({ reducer: { counter: counterReducer, }, }); export default store;

Bước 3: Cung cấp Store cho React

Mở file src/index.js và dùng Provider từ react-redux để cung cấp store cho toàn bộ ứng dụng React.

js
// src/index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import { Provider } from 'react-redux'; import store from './store/store'; import App from './App'; ReactDOM.createRoot(document.getElementById('root')).render( <Provider store={store}> <App /> </Provider> );

Bước 4: Sử dụng Redux trong Component

Bây giờ bạn có thể sử dụng Redux trong các component của mình. Mình sẽ hướng dẫn bạn làm một component đơn giản để tăng và giảm giá trị count.

js
// src/components/Counter.js import React from 'react'; import { useDispatch, useSelector } from 'react-redux'; const Counter = () => { // Dùng useSelector để lấy state từ Redux store const count = useSelector((state) => state.counter.count); // Dùng useDispatch để tạo hành động const dispatch = useDispatch(); return ( <div> <h1>Counter: {count}</h1> <button onClick={() => dispatch({ type: 'increment' })}>Tăng</button> <button onClick={() => dispatch({ type: 'decrement' })}>Giảm</button> </div> ); }; export default Counter;

Bước 5: Kết nối Component vào Ứng Dụng

Cuối cùng, bạn chỉ cần sử dụng component Counter trong file App.js:

js
// src/App.js import React from 'react'; import Counter from './components/Counter'; const App = () => { return ( <div> <Counter /> </div> ); }; export default App;

Chúc mừng bạn!

Giờ thì bạn có thể tăng và giảm giá trị count từ Redux store trong ứng dụng React của mình.

Bạn chỉ cần nắm vững các bước cơ bản trên, sau đó sẽ dễ dàng mở rộng thêm các tính năng phức tạp hơn. Nếu cần thêm thông tin hoặc có thắc mắc, cứ hỏi nhé!

Friday, February 14, 2025

Context React (Cách đơn giản nhất để truyền props trong React)

 Cách đơn giản nhất để truyền props trong React mà không cần truyền qua nhiều cấp là sử dụng Context API. Dưới đây là cách triển khai cực kỳ đơn giản:


🔹 1. Tạo Context

Tạo một file riêng, ví dụ: MyContext.js

jsx
import { createContext, useState } from "react"; export const MyContext = createContext(); export const MyProvider = ({ children }) => { const [message, setMessage] = useState("Hello from Context!"); return ( <MyContext.Provider value={{ message, setMessage }}> {children} </MyContext.Provider> ); };

🔹 2. Bọc App bằng Provider

Mở file app/layout.tsx (nếu dùng Next.js 14 App Router) hoặc index.js (React thường) và bọc toàn bộ ứng dụng bằng MyProvider:

jsx
import { MyProvider } from "./MyContext"; export default function RootLayout({ children }) { return ( <MyProvider> <html lang="en"> <body>{children}</body> </html> </MyProvider> ); }

🔹 3. Sử dụng Context ở Component con

Bất cứ component nào trong cây component đều có thể truy cập message:

jsx
import { useContext } from "react"; import { MyContext } from "./MyContext"; const ChildComponent = () => { const { message, setMessage } = useContext(MyContext); return ( <div> <h1>{message}</h1> <button onClick={() => setMessage("Context đã thay đổi!")}> Thay đổi Context </button> </div> ); }; export default ChildComponent;

Tóm lại:

  1. Tạo Context (MyContext.js)
  2. Bọc ứng dụng bằng Provider (layout.tsx hoặc index.js)
  3. Dùng useContext() để lấy dữ liệu ở bất kỳ component nào

Thế là xong! Không cần truyền props lằng nhằng qua từng component. 🚀