๐Ÿ“– TIL - Context API์™€ Redux Toolkit ๊ตฌํ˜„ ๊ฐ€์ด๋“œ ๐Ÿ“

์Š˜ยท2025๋…„ 2์›” 5์ผ

๐Ÿ“– TIL

๋ชฉ๋ก ๋ณด๊ธฐ
47/89

โœจ Context API ๊ตฌํ˜„ ์ˆœ์„œ

1. Context์™€ Provider ์ƒ์„ฑ

// LoginContext.js
import { createContext, useState } from "react";

export const LoginContext = createContext();
export const LoginProvider = ({ children }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <LoginContext.Provider value={{ isLoggedIn, setIsLoggedIn }}>
      {children}
    </LoginContext.Provider>
  );
};

2. App์— Provider ์ ์šฉ

// App.js
function App() {
  return (
    <LoginProvider>
      <Home />
    </LoginProvider>
  );
}

3. Context ์‚ฌ์šฉํ•˜๊ธฐ

const { isLoggedIn, setIsLoggedIn } = useContext(LoginContext);

๐Ÿš€ Redux Toolkit ๊ตฌํ˜„ ์ˆœ์„œ

1. ํŒจํ‚ค์ง€ ์„ค์น˜

npm install @reduxjs/toolkit react-redux

2. Store ์„ค์ •

// store.js
import { configureStore } from '@reduxjs/toolkit';
import todoReducer from './features/todoSlice';

export const store = configureStore({
  reducer: {
    todo: todoReducer,
  },
});

3. Slice ์ƒ์„ฑ

// todoSlice.js
const todoSlice = createSlice({
  name: 'todo',
  initialState,
  reducers: {
    addTodo: (state, action) => {
      state.todos.push(action.payload);
    },
    // ... ๋‹ค๋ฅธ ๋ฆฌ๋“€์„œ๋“ค
  },
});

4. Provider ์„ค์ •

function App() {
  return (
    <Provider store={store}>
      <App />
    </Provider>
  );
}

5. ์ปดํฌ๋„ŒํŠธ์—์„œ ์‚ฌ์šฉ

const dispatch = useDispatch();
const todos = useSelector((state) => state.todo.todos);

โญ๏ธ ์ฐธ๊ณ 

  • Context API๋Š” ๊ฐ„๋‹จํ•œ ์ „์—ญ ์ƒํƒœ ๊ด€๋ฆฌ์— ์ ํ•ฉ
  • Redux Toolkit์€ ๋ณต์žกํ•œ ์ƒํƒœ ๊ด€๋ฆฌ๋‚˜ ํฐ ๊ทœ๋ชจ์˜ ํ”„๋กœ์ ํŠธ์— ์ ํ•ฉ
profile
์ฃผ๋‹ˆ์–ด ํ”„๋ก ํŠธ์—”๋“œ ์„ฑ์žฅ๊ธฐ ๊ธฐ๋ก๊ธฐ๋ก

0๊ฐœ์˜ ๋Œ“๊ธ€