Getting Started With Redux Toolkit

image

React apps are used in large scale and managing state can be a challenge. React.Context is a great way to pass down data to child components using a Provider but it doesn’t allow children to pass up data

I will explain how Redux-Toolkit works under the hood. Now let’s visit Charlie’s Pizzeria to see how the staff operates like a global state to help us understand Redux’s workflow.

Terminology

Store

Store ( or the actual restaurant) is where the data is being held, like the customers, order numbers, produce, paperwork, supplies..etc

Dispatch

useDispatch() is a pre-typed tool from Redux Toolkit. Think of dispatch as the customer that is ready to place and order. The waiter writes it down and dispatches it to the kitchen crew, which in this case will be our reducers.

const dispatch = useDispatch()

const handleAddReservations = () => {
  if(!inputValue) return;
  dispatch(addReservation(inputValue))
  setInputValue("")
}

Reducers

Reducers are the chefs who prepares the food, updates the inventory and returns the order back to the customer. They take a the previous state value and payload to be used in the action, which processes the order.

Another example of state in this example is the produce inventory. When an order is placed, we will have to use some ingredients, track the inventory to know what exactly we have left to make more orders.

image

// Gets called by dispatch in component to change the state
addOrder:(state, action:PayloadAction<string>) => {
	
	// action = "Cook vegetarian pizza"
	state.value.push(action.payload) 
}

Hope this clears things up! If you have React and programming topics you’d like for me to cover, email me at christopher.clemmons2020@gmail.com

Want to start a project with me? Send a inquiry to hello@digyt.co or visit digyt.co/contact