Installing Redux and RTK in a React Application
In this lesson we will install the React-Redux package into our application, which allows React components to work in conjunction with Redux, and the Redux Toolkit (RTK for short).
Let's open our project and type the following command in the terminal:
npm install @reduxjs/toolkit react-redux
Now we need to create a store that will hold the global state of our application. First, in the src
folder, we will create a app
folder, and in it a store.js
file. Then, in this file, we need to import configureStore
from RTK:
import { configureStore } from '@reduxjs/toolkit'
Next, we'll create an empty store and pass in at least one reducer:
export default configureStore({
reducer: {}
)
In order for our React components to work with the store, we will do the following. Let's go to our main.jsx
file, which already contains the code:
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
In the import, we add lines with the store
created in the previous step and the Provider
component:
import store from './app/store'
import { Provider } from 'react-redux'
Then we wrap our main component App
in Provider
and pass it store
as a prop:
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
And finally, in the main React component App
we will place the following code:
function App() {
return <h2>This is my first Redux app!</h2>
}
export default App
We launch our project again and see in the browser window: 'This is my first Redux app!'
. We ignore the warning about the absence of a valid reducer for now. You did it, congratulations :).
Install Redux and RTK in your app as described in the tutorial. Make sure your app works.