Course Content
State Management with Redux Toolkit in React
State Management with Redux Toolkit in React
2. Applying Redux Toolkit in React
What AwaitsUnderstanding the Project Code and File StructureCreating the Redux StoreIntegrating the Redux Store Into the React AppInspecting the Store in the React AppUnderstanding Actions and Action CreatorsUnderstanding the Role of ReducersInspecting Actions and Reducers in ReduxConnecting Redux with React ComponentsCompleting the App
Connecting Redux with React Components
Theory
To establish a connection between React components and the Redux store, we can use the useSelector
hook to access the state and the useDispatch
hook for dispatching actions.
Practice
Now, let's connect the Counter component to the Redux store.
Code explanation:
- Line 2: Import the necessary hooks
useSelector
anduseDispatch
from thereact-redux
library. These hooks enable the connection between React and Redux; - Line 3: Import the
increment
anddecrement
action creators from the../redux/actions/counterAction
file. These actions will be dispatched to update the counter state in the Redux store; - Line 6: The
useSelector
hook is used to access thecounter
state from the Redux store. We provide a selector function as an argument, which returns the desired state value; - Line 7: The
useDispatch
hook is used to access Redux'sdispatch
function. It refers to thedispatch
function, which is used to dispatch actions to the Redux store; - Line 9-11: Define the event handler
handleIncrement
that is called when the "Increment" button is clicked. We dispatch theincrement
action to the Redux store inside the handler using thedispatch
function; - Line 13-15: Define the event handler
handleDecrement
that is called when the "Decrement" button is clicked. We dispatch thedecrement
action inside the handler to the Redux store using thedispatch
function; - Line 17-23: Render the JSX elements, including the current counter value and buttons for incrementing and decrementing. We attach the respective event handlers to the buttons'
onClick
attribute.
Note
This code connects a React component (
Counter
) to Redux. It usesuseSelector
to access the counter state anduseDispatch
to dispatch actions for state updates. The component displays the counter value and provides buttons to increment and decrement it. Clicking these buttons triggers actions that update the Redux store.
1. How do you establish a connection between React components and the Redux store for accessing state?
2. What is the purpose of the useSelector
hook in the code?
3. What does the handleDecrement
function do when called?
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 9