In the first part of these blog posts about Redux I gave a broad overview about three parts of an app the State the Actions and the Views. Continuing the intro to Redux I will go into more detail about what the three parts that we talked about in pt 1.
The State is the information in a web app. Any data type can be saved as a State variable. Using the calendar app example the State is the name of the event, date of it, and current timezone could also be a State.
Actions are JavaScript objects with a type field. Actions must have a type property with a string value that describes the action. And they usually have a payload property that describes the information related to the action. Here are examples of an action that includes a payload and one without. The remove all is self explanatory so it doesn’t typically require a payload description.
const addTodoAction = { type: 'todos/todoAdded',
payload: 'Buy milk'
}
const removeAllAction = { type: 'todos/removeAll'
}
To carry out these actions on the state you need to use a vanilla JavaScript function called a reducer function. The reducer function will define how the action used with the state will create a new state. Also the reducer function will return a default state if no action is provided, and will return the current state if it can’t recognize what the provided action is. Here’s an example from redux docs.
function Counter() { const[counter, setCounter] = useState(0) const increment = () => {
setCounter(prevCounter => prevCounter + 1)
} return (
<div> Value: {counter} <button onClick{increment}>Increment</button> </div> )
}