# Handling State with RTK

## Handling State with RTK&#x20;

Counter app example with Redux Toolkit

{% tabs %}
{% tab title="createSlice.js" %}

```javascript
// Importing the createSlice function
const { createSlice } = require("@reduxjs/toolkit");

// Initial state for the counter
const initialState = {
  count: 0,
};

// Creating a counter slice using the createSlice function
const counterSlice = createSlice({
  // Name of the slice
  name: "counter",

  // Initial state for the slice
  initialState: initialState,

  // Reducers define how the state should be updated based on dispatched actions
  reducers: {
    // Reducer for incrementing the count
    increment: (state, action) => {
      state.count++; // Incrementing the count property in the state
    },

    // Reducer for decrementing the count
    decrement: (state, action) => {
      state.count--; // Decrementing the count property in the state
    },
  },
});

// Exporting the reducer function generated by createSlice
module.exports = counterSlice.reducer;

// Exporting the actions generated by createSlice
module.exports.counterActions = counterSlice.actions;

```

{% endtab %}

{% tab title="store.js" %}

```javascript
const configureStore = require("@reduxjs/toolkit").configureStore;

const counterReducer = require("../features/counter/counterSlice");

// configuring store (providing the reducer to redux store)
const store = configureStore({
  reducer: {
    counter: counterReducer, // Assigning the counterReducer to the "counter" slice of the store
  },
});

module.exports = store;

```

{% endtab %}

{% tab title="index.js" %}

```javascript
const store = require("./app/store");
const { counterActions } = require("./features/counter/counterSlice");

// initial state
console.log(store.getState());

// subscribe to state changes
store.subscribe(() => {
  console.log(store.getState());
});

// disptach actions
store.dispatch(counterActions.increment());

store.dispatch(counterActions.increment());

store.dispatch(counterActions.decrement());
```

{% endtab %}
{% endtabs %}
