Welcome back to CodeYourCraft! Today, we're diving into the exciting world of React JS, focusing on a crucial aspect: Store and Dispatch. This concept is essential for managing and updating complex state in your React applications. Let's get started!
In simple terms, Store is a global data container in a React application, and Dispatch is a function that updates the state in the store.
As our applications grow, managing state becomes a challenge. Store and Dispatch help us centralize state management, making our code more organized and easier to maintain.
To create a store, we'll use a popular library called Redux. First, let's install it:
npm install reduxNow, let's create our store:
import { createStore } from 'redux';
// Create a simple reducer that manages our store 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 store with our reducer
const store = createStore(counterReducer);
// Get the current state from the store
const initialState = store.getState();
console.log(initialState); // { count: 0 }
š Note: In the above code, we've created a simple reducer that manages a counter state. The createStore function from Redux helps us create a store with our reducer.
Now that we have a store, let's learn how to dispatch actions to update our state:
// Dispatch an action to increment the counter
store.dispatch({ type: 'INCREMENT' });
// Dispatch an action to decrement the counter
store.dispatch({ type: 'DECREMENT' });
// Get the current state from the store
const currentState = store.getState();
console.log(currentState); // { count: 1 } or { count: -1 }š Note: In the above code, we're dispatching actions to increment and decrement our counter. When we dispatch an action, the corresponding case in our reducer is executed, and the state is updated accordingly.
To connect our components with the store, we'll use the connect function from react-redux. First, let's install it:
npm install react-reduxNow, let's connect our counter component:
import React from 'react';
import { connect } from 'react-redux';
// Our counter component
const Counter = ({ count }) => (
<div>
Count: {count}
</div>
);
// Map the state to our component's props
const mapStateToProps = state => ({ count: state.count });
// Connect our component to the store
export default connect(mapStateToProps)(Counter);š Note: In the above code, we've connected our counter component to the store using connect function from react-redux. The mapStateToProps function maps the state to our component's props.
What is a Store in the context of React JS?
That's it for today! In the next lesson, we'll dive deeper into Redux, explore more reducer patterns, and learn how to handle multiple actions. See you then! š