# Redux Global State Management `npm install redux` --- ## Functional Programming Functional programming is a paradigm of building computer programs using expressions and functions without mutating state and data. --- ## Redux Structure ``` - state - store - actions - reducers ``` --- ## State State the redux state is the single source of truth in your applicaion. This plain javaascript object is a representation of your projects current data aka the current state. `const state = {}` That's it. Your state is just a plain object. However, it is the very important to note that the state is READ-ONLY. We should not mutate the state directly. --- ## This is not allowed!!! ``` const state = {alias: Robin: name: Dick Grayson, isSideKick: true} /**...some application logic **/ state.alias = Night Wing state.isSideKick = !state.isSideKick ``` --- ## This is allowed!!! ``` const state = {alias: Robin: name: Dick Grayson, isSideKick: true} /**...some application logic that returns the state **/ return { ...state, alias : Night Wing } return { ...state, isSideKick: !state.isSideKick } ``` --- ## The Store A store is an object that holds the application's *state* tree. There should only be a single store in a Redux app, as the composition happens on the reducer level. The store uses the reducer to calculate the next version of the state. (more on the reducer later) ``` import { createStore } from 'redux' //usage const store = createStore(reducer) ``` --- ## Methods of the Store ``` - dispatch(action) - getState(): Will always return the most current state object - subscribe(listener) ``` --- ## Dispatch The only way to trigger a state change. Dispatch takes a paramter called an action. This parameter describes how the state is changing. --- ## Subscribe uses a change listener that will be called when actions are dispatched. (Note: a good place for logging) --- ## Actions A plain object describing the change that makes sense for your application. Actions are how you get changes into the store (change the state). Any data that needs to go into the store should use an action to get it there. `{type: SOME_ACTION, payload: {...}}` --- ## Reducer A pure functions that returns that next state tree. This function should not have any side effect manipulating. Ex: No loops, global variables, api calls etc. the reducers only job is to return you the correct copy of the state given the input. ``` cosnt reducer = (state = {}, action) => {..reducer logic} ```