What Is Redux?
What Is Redux?
What is Redux?
Redux is a state container for JavaScript apps. It is most commonly paired with
React, where it takes control of state away from React components and gives it
to a centralised place called a ‘store’.
Redux Flow
Before jumping into the code, it’s useful to think about how Redux is working
conceptually. The diagram below demonstrates the essential steps to Redux’s
process:
Redux 1
Step 1: UI (User Interface)
This is where a change is triggered. For example, a user clicking a ‘+’ button in
a simple counter app.
Step 2: Actions
The actual action we want to take place, for example, “add one”.
In Redux, actions are plain JavaScript objects, and they must have
a type property (e.g. 'ADD_ONE' ).
Step 3: Reducer
These specify how the application’s state should change in response to each
action. For example, our new state should be one integer higher than our old
state. It is reducers which give Redux its name — they share the same Latin
root).
Redux 2
The store brings everything together. It holds application state, and it is where
you will find three critical methods:
In our example of a counter app, the state object will contain whatever number
our counter is on. This change is then communicated back to the UI, where it
will appear to the user.
Additional Jargon
There are also a few more terms you’re likely to encounter when using Redux:
Redux 3
Boilerplate: sections of code that have to be included in many places with
little or no alteration. One of the reasons Redux can seem tricky to
beginners is because it contains more boilerplate than you’re likely used to
for front-end development.
Payload: the conventional name used for the property that holds the actual
data in a Redux action object. A payload isn’t necessary, but it’s fairly
common to see actions defined like this:
const ADD_USER = {
type: "ADD_USER",
payload: {name: "John Smith", age: 45},
}
File Structure
Finally, before diving into the code, we’ll take a quick look at file structure. The
fact that Redux’s boilerplate code tends to span multiple files can be one of the
most confusing parts for beginners. Redux is largely unopinionated, which
means there are endless ways to structure a Redux app. One of the simplest
options looks like this:
In reality, few apps are likely to have file structures as simple as the one above.
Below is a more scalable example.
Redux 4
Step 1: Setup your react project
You can set up a react project and configure babel, webpack on your
own or instead you can use create-react-app to spin up a react project, and
that is indeed what we are going to do now.
$npxcreate-react-app my-react-redux-app
Redux 5
TP - Tuto
Redux 6