Two Core Ideas in Redux
Before we start learning about the Redux library, let's get acquainted with two of its core ideas. The first idea, concerning state management, we will look at the example of a simple counter on the state in React:
function Counter() {
// State
const [count, setCount] = useState(0)
// Action:
function clickHandler() {
setCount(count + 1)
}
// View:
return (
<div>
<span>{count}</span>
<button onClick={clickHandler}>+</button>
</div>
)
}
In this code, we see the state for the variable count
- this is the source of truth for the counter. Then we see action, the event that causes the state to be updated when the user clicks. And finally, view, which is where we display the UI.
So the scheme is quite simple: the button is pressed - the state count
(State) changes upon pressing (Action), therefore the view (View) changes - in our case this is the number on the screen.
However, things get more complicated if we have multiple components that need to use the same state. Of course, you can, for example, lift the state to parent components, but this solution may not always solve the problem. In this case, Redux suggests that we create one place in the application that would contain the global state and certain behavior patterns when updating this state. This is exactly the first basic idea (!).
The second idea is related to immutability, that is, data immutability. You probably remember from JavaScript that arrays and objects can be changed. Changing data directly in Redux, as in other frameworks, is considered bad form and can lead to unpredictable consequences. Therefore, in Redux, our original objects and arrays must remain immutable, and we can only change their copies.
Tell us what the first basic idea of Redux is.
Tell us what the second core idea of Redux is.