redux와 styled-components를 써서 다크모드 전환을 구현하던 중 발생한 에러이다.
dispatcher is null
useContext@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:47773:7
useReduxContext@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:40821:75
useSelector@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:40910:9
./src/App.tsx@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:33:71
options.factory@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:59134:31
__webpack_require__@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:58557:33
fn@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:58791:21
./src/index.tsx@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:1177:81
options.factory@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:59134:31
__webpack_require__@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:58557:33
@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:59780:56
@https://reimagined-space-cod-4gw45qwg4w9hj6r4-3000.app.github.dev/static/js/bundle.js:59782:12
대충 이런 에러가 떳는데 에러 추적이 상당히 힘들었다.
터미널에선 정상적으로 실행되었다고 뜨는데 브라우저에서만 저 오류가 보인다.
로그를 보면 redux관련 오류인거 같은데 구글에선 자꾸 react router관련글만 보였다. (router관련해서도 해당 문제가 발생하는듯)
원인은 selector로 redux state를 가져오는 시점에 있었다.
import Router from "./Router/Router";
import { ThemeProvider } from "styled-components";
import { GlobalStyle } from "./global-style";
import lightTheme from "./styles/lightTheme";
import darkTheme from "./styles/darkTheme";
import { useSelector } from "react-redux";
import { RootState } from "./Redux/store";
const theme = useSelector((state: RootState) => state.themeReducer.value); <--이부분이 문제였다.
const App = () => {
return (
<ThemeProvider theme={theme ? darkTheme : lightTheme}>
<GlobalStyle />
<Router />
</ThemeProvider>
);
};
export default App;
theme value를 가져오는 위치를 보면 app 컴포넌트를 렌더링하는 함수 바깥에 선언되어 있는데
이때문에 redux 컴포넌트들이 초기화 되기도 전에 dispatcher를 사용하려고 해서 발생한 오류로 추정된다.
import Router from "./Router/Router";
import { ThemeProvider } from "styled-components";
import { GlobalStyle } from "./global-style";
import lightTheme from "./styles/lightTheme";
import darkTheme from "./styles/darkTheme";
import { useSelector } from "react-redux";
import { RootState } from "./Redux/store";
const App = () => {
const theme = useSelector((state: RootState) => state.themeReducer.value);
return (
<ThemeProvider theme={theme ? darkTheme : lightTheme}>
<GlobalStyle />
<Router />
</ThemeProvider>
);
};
export default App;
이렇게 app컴포넌트 안으로 넣어주니 말끔히 해결이 되었다.