각각의 React 컴포넌트 파일에서 동일한 이름의 state를 사용해도 괜찮을까?
YES.
두 컴포넌트 간에 state를 공유해야 하는 경우라면?
function Parent() {
const [sharedCount, setSharedCount] = useState(0);
return (
<>
<ChildA count={sharedCount} setCount={setSharedCount} />
<ChildB count={sharedCount} setCount={setSharedCount} />
</>
);
}
const CountContext = React.createContext();
function CountProvider({ children }) {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={{ count, setCount }}>
{children}
</CountContext.Provider>
);
}
// 사용하는 컴포넌트에서
function ChildComponent() {
const { count, setCount } = useContext(CountContext);
// ...
}
복잡한 애플리케이션에서 더 체계적인 상태 관리가 필요할 때 사용
Redux, Recoil, MobX 등이 있음
Redux 예시 코드
// store 생성
const store = createStore(rootReducer);
// Provider로 앱 전체를 감싸기
<Provider store={store}>
<App />
</Provider>
// 컴포넌트에서 사용
function Component() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
// ...
}