Getting Started With Redux
Table of contents
Prerequisites: Create a react-app using create-react-app
What is Redux?
Redux is a predictable state container for JavaScript applications. It is often used in combination with React but can be used with any other JavaScript framework or library as well.
The main idea behind Redux is to have a centralized store that holds the state of the entire application. This makes it easy to manage the state of the application and allows for easy communication between different parts of the application. We mainly use Redux to manage the state in a larger application.
How to Implement Redux?
To implement react at first we have to install redux.
Write the following code in your terminal.
So, you implement redux in your application, now you can apply it to your project. Let's go and see how can we apply redux in our application...
How to Use Redux?
First, create all the folders and file like the below:
We created pages and store folder under the src folder, under the pages we will create all the pages that we show in our application and under the store we created a slices folder and index.js file. under the slices folder e take all the slice(means reducer functions) and in index.js we store all the slices. For better understanding follow the code below.
First, we create our Counter.js and App.js pages like this...
We create a function that increases and decrease the value in the span
of clicking the buttons.
Let's write the function in CounterCount.slice.js file like below.
Here counterSlice takes 3 things name, initialState and reducers. Under the reducers we can write functions, these functions take to parameters state and action, state is our initial state and action is what we pass in our function as action.payload. Here when we pass anything in our action.payload will increment or decrement with our state according to the function.
Now, it's time to write index.js that will play as store.
Here we take all the slices with the help of configureStore.
After that wrapped the react-redux in the main index.js file like this.
Here store means the total of all slices that are present in the index.js.
Now, it's time to wrap up the application to apply those functions in Counter.js like below...
Here we can use the function and state with the help of dispatch that we get from useDispatch()
hook and the value that gets from the useSelector()
hook respectively.
This is all about Redux. Run the code and see how it works...
Overall, Redux is a valuable tool for developers who want to manage state consistently and predictably across their applications.