Need of a state management library
What's the need for a state management library? can't we go with the useState hook provided by React to manage the states of our component?
Answer: To avoid the prop drilling we must use a state management library.
Redux
Redux is a state container for JavaScript apps, using redux we can manage the state of our app.
The whole redux logic requires four things:
- Store : A "store" is a js object that holds the application's global state
- Dispatch : dispatch is a method we need to call inorder to update our state
- Action : action is an object that describes "something that happened in the application"
- Reducers: reducers are functions where we write how our state should be updated based on the action provided.
Whenever an action is dispatched, the store will call the reducer function and based on the action provided the state will be updated.
Redux-toolkit
redux-toolkit is the official recommended approach for writing redux logic. redux-toolkit simplifies setting up the redux logic in react.
What issues does redux-toolkit solve?
- Configuring a Redux store is too complicated
- Redux requires too much boilerplate code
Installation
Step1 : Create Store
Step2: Provide the store to React
Step3: Create a redux state slice
Step4: Add Slice reducer to the store
Step5: Use redux state in the components
createAsyncThunk for the api calls
A function that accepts a Redux action type string and a callback function that should return a promise.