라이브러리&프레임워크/React

import {Provider} from 'react-redux' 에 대해

youngble 2021. 11. 24. 01:41

리덕스의 store 를 사용하기위해서 index.js 에 {Provider} 를 import 하는걸 볼수있는데 이것이 무엇인지 나오지 않았다.

공식문서를 통해 무엇인지 보면 다음과같다

Passing the Store with Provider

Our components can now read state from the store, and dispatch actions to the store. However, we're still missing something. Where and how are the React-Redux hooks finding the right Redux store? A hook is a JS function, so it can't automatically import a store from store.js by itself.

Instead, we have to specifically tell React-Redux what store we want to use in our components. We do this by rendering a <Provider> component around our entire <App>, and passing the Redux store as a prop to <Provider>. After we do this once, every component in the application will be able to access the Redux store if needs to.

https://ko.redux.js.org/tutorials/fundamentals/part-5-ui-react/#passing-the-store-with-provider

 

Redux 기반, Part 5: UI and React | Redux

The official Redux 기반 튜토리얼: learn how to use Redux with React

ko.redux.js.org

 

리듀서와 스토어를 다 만들었다고해서 hook을 이용해서 올바른 리덕스 스토어를 쓰고 있는지 어디에서 어떻게 쓰는지는 정해지지 않았다. 훅은 자바스크립트 함수이기때문에 store.js 에서 자동으로 import 할수없다. 그래서 리액트 리덕스에게 우리 컴포넌트에서 무슨 스토어를 쓰고싶은지 설정해줘야한다고 한다. 그때 하는  <Provider>를 전체통합인 <App>컴포넌트를 감싸주고 랜더링 해주면서 설정한다. 그리고 그때 그 Provider 부분에 prop으로써 리덕스 스토어를 passing 해주는것이다. store ={store} 이런식으로 한번하고나면 모든 컴포넌트는 어플리케이션에서 리덕스 스토어에 접근이 가능하다고한다. 

 

그다음은 어떤 핵심 키워드를 사용하는지 설명해준다.

 

That covers the key parts of using React-Redux with React:

  • Call the useSelector hook to read data in React components
  • Call the useDispatch hook to dispatch actions in React components
  • Put <Provider store={store}> around your entire <App> component so that other components can talk to the store

리액트 컴포넌트에서 데이터를 읽기위해 useSelector 훅을 호출하고, 리액트 컴포넌트들안에서 액션을 디스패치하기위해 useDispatch 를 호출하라고한다. 그다음은 위의 설명처럼 provider 태그를 쓰는걸 보여준다