ReasonJun

Redux : Provider / useSelector / useDispatch 본문

Frontend/Redux

Redux : Provider / useSelector / useDispatch

ReasonJun 2023. 8. 19. 15:10
728x90

Provider

is a React component that makes the Redux store available to all of its child components. It is used to connect the Redux store to the React component tree.

The syntax for using Provider is as follows:

import { Provider } from 'react-redux';

const App = () => {
  const store = createStore(reducer);

  return (
    <Provider store={store}>
      <MyComponent />
    </Provider>
  );
};

In this example, the Provider component is used to make the store variable available to the MyComponent component. The MyComponent component can then use the store variable to access the Redux state and dispatch actions.

 

 

useSelector

is a React hook that allows you to select a piece of state from the Redux store. It takes a selector function as an argument, and the selector function returns the piece of state that you want to select.

The syntax for using useSelector is as follows:

const selectedState = useSelector(selectorFunction);

In this example, the selectorFunction is a function that takes the current state as an argument and returns the piece of state that you want to select. The selectedState variable will then contain the value of the selected state.

 

 

useDispatch

is a React hook that allows you to dispatch an action to the Redux store. It takes an action creator function as an argument, and the action creator function returns an action that can be dispatched to the store.

The syntax for using useDispatch is as follows:

const dispatch = useDispatch();

dispatch(actionCreatorFunction());

In this example, the actionCreatorFunction is a function that returns an action that can be dispatched to the store. The dispatch function then dispatches the action to the store.

 

Here is a table that summarizes the differences between Provider, useSelector, and useDispatch:

Feature Provider useSelector useDispatch
Purpose Makes the Redux store available to all child components Selects a piece of state from the Redux store Dispatches an action to the Redux store
Syntax <Provider store={store}> const selectedState = useSelector(selectorFunction) const dispatch = useDispatch()
When to use When you want to make the Redux store available to all child components When you want to select a piece of state from the Redux store When you want to dispatch an action to the Redux store
728x90

'Frontend > Redux' 카테고리의 다른 글

Redux: toolkit  (0) 2023.08.19
Redux : middleware / Thunk  (0) 2023.08.19
Redux: CombineReducers  (0) 2023.08.19
Redux: strict unidirectional data flow  (0) 2023.08.19
Redux : What is Redux  (0) 2023.08.19
Comments