Contenido del Curso
Expert React
Expert React
Involve Redux into React
Step 5: Connect Redux and React
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.
Complete code
Please, take a moment to scrutinize all files and folders. So the process was clear and understandable
¡Gracias por tus comentarios!