Outline
This tutorial is a part of the "Build a Real World App with React & Redux" tutorial series.
What is Redux?
Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. -Redux Docs
If you're not familiar with the idea of "state" in React (or programming in general), take a peek at the lesson we made about it.
The fundamental concepts in Redux are called "stores" and "actions". A store has two parts: a plain-old JavaScript object that represents the current state of your application, and a "reducer", which is a function that describes how incoming actions modify your state.
Before we can start writing any code, we'll need to have our boilerplate app up and running (run npm install
and then npm start
after cloning)
git clone -b 00 git@github.com:gothinkster/react-redux-realworld-example-app.git
Creating a Store
To create a store that represents the state of a checkbox, let's create a
default state, a reducer that allows actions of type 'TOGGLE' to change
the state, and finally use redux's createStore()
function to create a new
store.
src/index.js
import ReactDOM from 'react-dom';
import React from 'react';
+ import { createStore } from 'redux';
+ const defaultState = { checked: false };
+ const reducer = function(state = defaultState, action) {
+ switch (action.type) {
+ case 'TOGGLE':
+ return { ...state, checked: !state.checked };
+ }
+ return state;
+ };
+ const store = createStore(reducer);
class App extends React.Component {
render() {
return (
<h1>Hello, World!</h1>
);
}
}
ReactDOM.render((
<App />
), document.getElementById('root'));
Note that the reducer receives both the current state and the action as parameters, and returns the modified state. A well-written reducer should not have any side-effects, that is, if you call a reducer with the same state and the same action, you should always get the same result. Reducers should not modify or rely on any global state. It's also good practice to encapsulate as much of your application logic as possible in reducers, because, since your reducers don't rely on side-effects or global state, they're really easy to test, debug, and refactor.