프로젝트를 만드는중 무수히 많아지는 state들을 매번 자식으로 넘겨주는 과정이 매우 번거롭게 느껴졌다. 그래서 많이 사용하는 redux를 공부해보자
//store.js
import { createStore } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
const INITIAL_STATE = {
name: "ktw",
};
const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case "CLICK_CELL":
return {
...state,
name: state.name,
};
}
};
export const store = createStore(reducer, composeWithDevTools());
//index.js
import {store} from './store'
ReactDom.render(
<>
<Provider store={store}>
<App />
</Provider>
</>,
document.querySelector("#root")
);
//App.js
import {useSelector, useDispatch} from 'react-redux'
const App = () => {
const item = useSelector((state) => state);
const dispatch = useDispatch();
return(
{item.name} //ktw가 출력됨
)
}
//store.js
import {combineReducers} from 'redux'
const state01 = { name : "김태완"}
const state02 = { nickname : "부디"}
const nameReducer = (state = state01, action) => {
switch (action.type) {
case "CHANGE":
return {
...state,
name: "김.태.완",
};
default:
return state;
}
};
const nicknameReducer = (state = state02, action) => {
switch (action.type) {
case "CHANGE":
return {
...state,
name: "부.디",
};
default:
return state;
}
};
const rootReducer = combineReducers({
name: nameReducer,
nickname: nicknameReducer,
});
const store = createStore(rootReducer, composeWithDevTools());
console.log(store.getState())