Welcome ðŸŽ‰

logo

ReactLMS

Search
Light Mode
Contact Us

3 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Concept


Redux Toolkit is an official toolkit of Redux, which helps simplify the usage of Redux and reduce the complexity of Redux configuration. It provides APIs and utilities to write Redux code that is concise, readable, and understandable. Redux Toolkit includes features such as automatic reducer generation, automatic action generation, and support for handling asynchronous tasks.

To learn more about Redux Toolkit, we need to clarify the following terms:


Example


Here is a simple example of how to use Redux Toolkit in a React application:

Installing Redux Toolkit:

npm install @reduxjs/toolkit






Create a file counterSlice.js to create a reducer and action with createSlice:

// counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => {
      return state + 1;
    },
    decrement: (state) => {
      return state - 1;
    },
  },
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;






Create a file store.js to create a Redux store with configureStore:

// store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

export default store;






Using Redux Toolkit in a React application:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counterSlice';

function App() {
  const count = useSelector((state) => state.counter);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
    </div>
  );
}

export default App;






In the example above, we used createSlice to create a reducer and action for the counter. configureStore is used to create a Redux store with the corresponding reducer. In the App component, we use the useSelector hook to get the state from the store and the useDispatch hook to send actions to the reducer.


Read more
On This Page