Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Involve Redux into React | Redux Toolkit
Expert React
course content

Conteúdo do Curso

Expert React

Expert React

1. React Key Concepts
2. React Router
3. Redux Toolkit
4. Formik
5. Jest
6. Next Steps

bookInvolve 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 and useDispatch from the react-redux library. These hooks enable the connection between React and Redux.
  • Line 3: Import the increment and decrement 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 the counter 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's dispatch function. It refers to the dispatch 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 the increment action to the Redux store inside the handler using the dispatch function.
  • Line 13-15: Define the event handler handleDecrement that is called when the "Decrement" button is clicked. We dispatch the decrement action inside the handler to the Redux store using the dispatch 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 uses useSelector to access the counter state and useDispatch 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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 7
some-alt