728x90
반응형
기본적인 세팅
redux 라이브러리 설치 및 의존성 주입
npm
npm install redux react-redux
yarn
yarn add redux react-redux
파일 생성 및 기본 틀 생성
저장소 생성 (store)
// src/store/index.js
import { createStore } from 'redux';
import rootReducer from '../reducers'; // 루트 리듀서
const store = createStore(rootReducer);
export default store;
reducers 생성 (reducers)
// src/reducers/index.js
import { combineReducers } from 'redux';
import someReducer from './someReducer';
const rootReducer = combineReducers({
// 여러 개의 리듀서를 합침
someReducer,
});
export default rootReducer;
특정 reducer 생성(reducer)
// src/reducers/someReducer.js
const initialState = {
// 초기 상태 정의
someState: initialValue,
};
const someReducer = (state = initialState, action) => {
switch (action.type) {
case 'SOME_ACTION':
return {
...state,
// 상태 업데이트 로직 작성
};
default:
return state;
}
};
export default someReducer;
import { Provider, useSelecotor, useDispatch, connect } from 'react-redux'; and use
Provider 사용하기
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store'; // Redux store
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
Connect 컴포넌트로 상태 연결
// src/components/SomeComponent.js
import React from 'react';
import { connect } from 'react-redux';
const SomeComponent = ({ someState }) => {
return (
<div>
<h1>Some Component</h1>
<p>Some state: {someState}</p>
</div>
);
};
const mapStateToProps = (state) => ({
someState: state.someReducer.someState,
});
export default connect(mapStateToProps)(SomeComponent);
useSelector 사용하기
import React from 'react';
import { useSelector } from 'react-redux';
const MyComponent = () => {
const someState = useSelector(state => state.someReducer.someState);
return (
<div>
<p>Some state: {someState}</p>
</div>
);
};
export default MyComponent;
useDispatch 사용하기
import React from 'react';
import { useDispatch } from 'react-redux';
const MyComponent = () => {
const dispatch = useDispatch();
const handleClick = () => {
dispatch({ type: 'SOME_ACTION', payload: someData });
};
return (
<div>
<button onClick={handleClick}>Dispatch Action</button>
</div>
);
};
export default MyComponent;
728x90
반응형
'📁 𝐫𝐮𝐧𝐭𝐢𝐦𝐞𝐄𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭 > React.js' 카테고리의 다른 글
[React .hook] How to use useReducer ? (0) | 2024.02.21 |
---|---|
[React .hook] What is useReducer ? (0) | 2024.02.21 |
[React .library] what is Redux ? (0) | 2024.02.20 |
[React .hook] How to use useContext ? (0) | 2024.02.19 |
[React .hook] What is useContext ? (0) | 2024.02.19 |