Software Development/Front-end

[Redux] Cannot read properties of null (reading 'useContext')

es6.kr 2024. 1. 31. 16:03
반응형

Redux 설정 시 store.js에서 리듀서 추가 누락 오류

React 프로젝트에서 Redux를 설정할 때, store.js 파일에 combineReducers로 리듀서를 추가하지 않으면 다음과 같은 오류가 발생한다. 이 오류는 React의 useContext 훅을 사용하는 과정에서 발생한다.

오류 메시지:

Cannot read properties of null (reading 'useContext') && react.development.js:209 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

이 오류는 Redux 설정 시 리듀서를 combineReducers로 제대로 합치지 않았을 때 발생한다. 리듀서가 제대로 등록되지 않으면 useContext 훅이 예상한 값을 반환하지 못하고, 그로 인해 오류가 발생한다.

오류 해결 방법

이 문제를 해결하려면 store.js에서 리듀서를 combineReducers로 정확하게 추가해야 한다. 리듀서를 올바르게 설정하면 오류가 해결된다.

예시 코드:

// store.js

import { createStore, combineReducers } from 'redux';
import { providerReducer } from './reducers';

const rootReducer = combineReducers({
  provider: providerReducer,
  // 다른 리듀서들도 여기에 추가할 수 있다.
});

const store = createStore(rootReducer);

export default store;

combineReducers에 리듀서를 추가하지 않으면 Redux가 상태를 제대로 관리할 수 없게 되고, 이로 인해 위와 같은 오류가 발생한다.


참고 자료

더 자세한 해결 방법은 StackOverflow에서 확인할 수 있다:
How to fix cannot read properties of null (reading 'useContext')?

반응형