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`).
Comments