일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 무한 스크롤
- 투포인터
- SSR
- Jest
- map
- 인터섹션
- 리터럴 타입
- dfs
- 공변성
- TS
- CORS
- webpack
- React
- 타입 좁히기
- 이분 검색
- Cypress
- async/await
- recoil
- 태그된 유니온
- 결정 알고리즘
- app router
- CI/CD
- RTK Query
- autosize
- tailwind
- ESlint
- 반공변성
- Promise
- 호이스팅
- useAppDispatch
- Today
- Total
짧은코딩
리액트와 리덕스 연결하기, redux devtools 본문
폴더 구조
https://shortcoding.tistory.com/396
redux-thunk
간단한 것은 thunk로 구현할 수 있지만 복잡한 것은 saga로 구현하는 것이 좋다. thunkMiddleware // thunkMiddleware는 아래 코드가 끝이라서 불러올 가치가 없다 // 기본적으로 action은 객체 const thunkMiddleware
shortcoding.tistory.com
이 글에서 만들었던 actions와 reducers를 가져와서 사용했다.
다른 점이 있다면 index.js 파일은 store.js로 바꾸고 module로 바꿨다.
client.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.querySelector('#root'),
);
react-redux 라이브러리에서 Provider을 사용하여 redux와 연결할 수 있다.
구조를 보면 useContext와 비슷한 구조를 띄고 있는 것을 알 수 있다. useContext도 사용하다보면 결국 redux의 모습을 만들고 있기 때문에 처음부터 redux를 사용하는 것이 좋다.
App.jsx
import React, { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
const { logIn, logOut } = require('./actions/user');
const App = () => {
const user = useSelector((state) => state.user);
const posts = useSelector((state) => state.posts);
const dispatch = useDispatch();
const onClick = useCallback(() => {
dispatch(logIn({
id: 'zerocho',
password: '비밀번호',
}));
}, []);
const onLogout = useCallback(() => {
dispatch(logOut());
}, []);
return (
<div>
{user.isLoggingIn
? <div>로그인 중</div>
: user.data
? <div>{user.data.nickname}</div>
: '로그인 해주세요.'}
{!user.data
? <button onClick={onClick}>로그인</button>
: <button onClick={onLogout}>로그아웃</button>}
</div>
);
};
export default App;
useDispatch: dispatch를 의미하며 action을 실행할 수 있다.
useSelector: 가져오고 싶은 데이터를 가져올 수 있다.
결과
-로그인 버튼 누르기 전
-로그인 버튼 누르고
-로그아웃 버튼 누르고
LOG_OUT 로깅이 추가된 것을 볼 수 있다.
redux devtools
redux devtools는 한 동작을 할 때마다 데이터가 어떻게 바뀌는지 디버깅을 할 수 있는 것이다.
-설치
npm i redux-devtools-extension -D
-D를 붙여서 개발자 모드로 설치하는 것이 좋다. 그렇지 않으면 사용자들이 devtools로 전체적인 데이터를 볼 수 있어서 해킹의 위험이 있다.
개발자 도구에서 데이터의 변화를 알 수 있다.
보통 Diff와 State를 많이 사용한다.
Diff: 뭐가 바뀌었는지 보여주는 것
State: 전체 상태를 보여준다.
-store.js
const enhancer = process.env.NODE_ENV === 'production'
? compose(
applyMiddleware(
firstMiddleware,
thunkMiddleware,
),
)
: composeWithDevTools(
applyMiddleware(
firstMiddleware,
thunkMiddleware,
),
);
enhancer 함수에서 개발 환경에서는 compose 대신 composeWithDevTools를 사용하면 된다.
'인프런, 유데미 > Redux' 카테고리의 다른 글
redux-toolkit (0) | 2022.11.19 |
---|---|
immer(코드를 줄일 수 있음) (0) | 2022.11.18 |
redux-thunk (0) | 2022.11.18 |
리덕스 미들웨어 (0) | 2022.09.13 |
리덕스 내부 구조 잡기 (0) | 2022.09.10 |