Blog>
Snippets

Initializing the Redux Store with RTK 2.0

Showcase the basic setup of a Redux store using the new Redux Toolkit 2.0 configuration and root reducer registration.
<!DOCTYPE html>
<html>
<head>
    <title>Redux Toolkit Example</title>
    <script src="https://cdn.jsdelivr.net/npm/@reduxjs/toolkit@latest/dist/redux-toolkit.umd.min.js"></script>
    <script src="app.js" defer></script>
</head>
<body>
    <!-- Your HTML here -->
</body>
</html>
HTML boilerplate including the Redux Toolkit CDN and a reference to the external JavaScript file 'app.js' where the Redux code will be placed.
/* app.js */
// Import configureStore and createSlice from Redux Toolkit
const { configureStore, createSlice } = ReduxToolkit;

// Create a slice with a reducer and initial state
const exampleSlice = createSlice({
  name: 'example',
  initialState: { value: 0 },
  reducers: {
    increment: state => {
      state.value += 1;
    }
  }
});

// Destructure the actions from the slice
const { increment } = exampleSlice.actions;

// Create a Redux store with the slice reducer
const store = configureStore({
  reducer: exampleSlice.reducer
});

// Dispatch an action to test
store.dispatch(increment());

// Log the initial state
console.log(store.getState());
This is the JavaScript ('app.js') that initializes the Redux store with a basic slice reducer using Redux Toolkit 2.0. It defines an example slice with an increment action, configures the store, dispatches an action to increment the state, and logs the initial state.