Skip to main content
Home
Drupal life hacks

Main navigation

  • Drupal
  • React
  • WP
  • Contact
  • About
User account menu
  • Log in

Breadcrumb

  1. Home

Understanding Redux: createStore Function

By admin, 5 April, 2024

The `createStore` function in Redux is used to create a Redux store, which is the core object for managing the state of your application. Here's an example of using `createStore` in Redux:

import { createStore } from 'redux';
// A reducer is a function that takes the current state and an action, and returns the new state
const counterReducer = (state = { count: 0 }, action) => {
 switch (action.type) {
   case 'INCREMENT':
     return { count: state.count + 1 };
   case 'DECREMENT':
     return { count: state.count - 1 };
   default:
     return state;
 }
};
// Create a Redux store using createStore, passing the reducer as an argument
const store = createStore(counterReducer);
// The getState method is used to get the current state of the store
console.log(store.getState()); // { count: 0 }
// An action is an object that contains a type and possibly additional data
const incrementAction = { type: 'INCREMENT' };
// The dispatch method is used to dispatch an action to the store
store.dispatch(incrementAction);
console.log(store.getState()); // { count: 1 }

In this example, `createStore` takes the `counterReducer` reducer as an argument and creates a Redux store. The reducer defines how the application state changes in response to actions. Then, we can use the store to get the current state (`getState`) and dispatch actions (`dispatch`).

Tags

  • React

Comments

About text formats

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
Powered by Drupal