Before starting off make sure to have a React development environment in place. First, create react app,
npx create-react-app react-redux-tutorial
Once done you’re good to go.
What is Redux? To answer that question we must first talk about state in JavaScript web applications. Consider a simple user flow:
“as a user I can click a button named Click me and a modal should appear soon after”.
Guess what, even in this trivial interaction there is a state we must deal with. For example, we can describe the initial state of the app as a plain JavaScript object:
const state = {
buttonClicked: 'no',
modalOpen: 'no'
}
When the user clicks, the state changes and we have:
const state = {
buttonClicked: 'yes',
modalOpen: 'yes'
}
How do you reliably keep track of these state changes? What if the state is mutated by accident by some unrelated piece of logic? Is there a library that can help us?
Also, if you worked with React before the term state should be no surprise to you. I guess you already wrote some “stateful” React component like this:
import React, { Component } from "react";
class ExampleComponent extends Component {
constructor(props) {
super(props);
this.state = {
articles: [
{ title: "React Redux Tutorial for Beginners", id: 1 },
{ title: "TypeScript tutorial for beginners", id: 2 }
]
};
}
render() {
const { articles } = this.state;
return <ul>{articles.map(el => <li key={el.id}>{el.title}</li>)}</ul>;
}
}
A stateful React component is a JavaScript class (with React hooks that’s no longer the case).
In a React component, the state holds data that can be rendered to the user. The state in React could also change in response to actions and events: in fact, you can update the local component’s state with this.setState()
.
So, in general, a typical JavaScript application is full of state. For example, the state is:
Having seen the basics let’s now talk about what problem Redux tries to solve.
#react #programming #front-end-development #javascript #redux #react native