Usage with React

    That said, Redux works especially well with libraries like and Deku because they let you describe UI as a function of state, and Redux emits state updates in response to actions.

    We will use React to build our simple todo app, and cover the basics of how to use React with Redux.

    are not included in Redux by default. You need to install them explicitly:

    If you don't use npm, you may grab the latest UMD build from unpkg (either a development or a build). The UMD build exports a global called if you add it to your page via a <script> tag.

    Presentational and Container Components

    React bindings for Redux separate presentational components from container components. This approach can make your app easier to understand and allow you to more easily reuse components. Here's a summary of the differences between presentational and container components (but if you're unfamiliar, we recommend that you also read ):

    Most of the components we'll write will be presentational, but we'll need to generate a few container components to connect them to the Redux store. This and the design brief below do not imply container components must be near the top of the component tree. If a container component becomes too complex (i.e. it has heavily nested presentational components with countless callbacks being passed down), introduce another container within the component tree as noted in the FAQ.

    Technically you could write the container components by hand using . We don't advise you to do this because React Redux makes many performance optimizations that are hard to do by hand. For this reason, rather than write container components, we will generate them using the connect() function provided by React Redux, as you will see below.

    Our design brief is simple. We want to show a list of todo items. On click, a todo item is crossed out as completed. We want to show a field where the user may add a new todo. In the footer, we want to show a toggle to show all, only completed, or only active todos.

    I see the following presentational components and their props emerge from this brief:

    • TodoList is a list showing visible todos.
      • todos: Array is an array of todo items with { id, text, completed } shape.
      • onTodoClick(id: number) is a callback to invoke when a todo is clicked.
    • Todo is a single todo item.
      • text: string is the text to show.
      • completed: boolean is whether the todo should appear crossed out.
      • onClick() is a callback to invoke when the todo is clicked.
    • Link is a link with a callback.
      • onClick() is a callback to invoke when the link is clicked.
    • Footer is where we let the user change currently visible todos.
    • App is the root component that renders everything else.
      They describe the look but don't know where the data comes from, or how to change it. They only render what's given to them. If you migrate from Redux to something else, you'll be able to keep all these components exactly the same. They have no dependency on Redux.

    Designing Container Components

    We will also need some container components to connect the presentational components to Redux. For example, the presentational TodoList component needs a container like VisibleTodoList that subscribes to the Redux store and knows how to apply the current visibility filter. To change the visibility filter, we will provide a FilterLink container component that renders a Link that dispatches an appropriate action on click:

    • VisibleTodoList filters the todos according to the current visibility filter and renders a TodoList.
    • FilterLink gets the current visibility filter and renders a Link.
      • filter: string is the visibility filter it represents.

    Sometimes it's hard to tell if some component should be a presentational component or a container. For example, sometimes form and function are really coupled together, such as in the case of this tiny component:

    • AddTodo is an input field with an “Add” button
      Technically we could split it into two components but it might be too early at this stage. It's fine to mix presentation and logic in a component that is very small. As it grows, it will be more obvious how to split it, so we'll leave it mixed.

    Implementing Components

    Let's write the components! We begin with the presentational components so we don't need to think about binding to Redux yet.

    Implementing Presentational Components

    These are all normal React components, so we won't examine them in detail. We write functional stateless components unless we need to use local state or the lifecycle methods. This doesn't mean that presentational components have to be functions—it's just easier to define them this way. If and when you need to add local state, lifecycle methods, or performance optimizations, you can convert them to classes.

    components/Todo.js

    1. import React from 'react'
    2. import PropTypes from 'prop-types'
    3. const Todo = ({ onClick, completed, text }) => (
    4. <li
    5. onClick={onClick}
    6. style={{
    7. textDecoration: completed ? 'line-through' : 'none'
    8. }}
    9. >
    10. {text}
    11. </li>
    12. )
    13. Todo.propTypes = {
    14. onClick: PropTypes.func.isRequired,
    15. completed: PropTypes.bool.isRequired,
    16. text: PropTypes.string.isRequired
    17. }
    18. export default Todo

    components/TodoList.js

    1. import React from 'react'
    2. import PropTypes from 'prop-types'
    3. import Todo from './Todo'
    4. const TodoList = ({ todos, onTodoClick }) => (
    5. <ul>
    6. {todos.map((todo, index) => (
    7. <Todo key={index} {...todo} onClick={() => onTodoClick(index)} />
    8. ))}
    9. </ul>
    10. )
    11. TodoList.propTypes = {
    12. todos: PropTypes.arrayOf(
    13. PropTypes.shape({
    14. completed: PropTypes.bool.isRequired,
    15. text: PropTypes.string.isRequired
    16. }).isRequired
    17. ).isRequired,
    18. onTodoClick: PropTypes.func.isRequired
    19. }
    20. export default TodoList
    1. import React from 'react'
    2. import PropTypes from 'prop-types'
    3. const Link = ({ active, children, onClick }) => {
    4. if (active) {
    5. return <span>{children}</span>
    6. }
    7. <a
    8. href=""
    9. onClick={e => {
    10. e.preventDefault()
    11. onClick()
    12. }}
    13. >
    14. {children}
    15. </a>
    16. )
    17. }
    18. Link.propTypes = {
    19. active: PropTypes.bool.isRequired,
    20. children: PropTypes.node.isRequired,
    21. onClick: PropTypes.func.isRequired
    22. }
    23. export default Link

    Now it's time to hook up those presentational components to Redux by creating some containers. Technically, a container component is just a React component that uses store.subscribe() to read a part of the Redux state tree and supply props to a presentational component it renders. You could write a container component by hand, but we suggest instead generating container components with the React Redux library's function, which provides many useful optimizations to prevent unnecessary re-renders. (One result of this is that you shouldn't have to worry about the React performance suggestion of implementing shouldComponentUpdate yourself.)

    To use connect(), you need to define a special function called mapStateToProps that describes how to transform the current Redux store state into the props you want to pass to a presentational component you are wrapping. For example, VisibleTodoList needs to calculate todos to pass to the TodoList, so we define a function that filters the state.todos according to the state.visibilityFilter, and use it in its mapStateToProps:

    1. const getVisibleTodos = (todos, filter) => {
    2. switch (filter) {
    3. case 'SHOW_COMPLETED':
    4. return todos.filter(t => t.completed)
    5. case 'SHOW_ACTIVE':
    6. return todos.filter(t => !t.completed)
    7. case 'SHOW_ALL':
    8. default:
    9. return todos
    10. }
    11. }
    12. const mapStateToProps = state => {
    13. return {
    14. todos: getVisibleTodos(state.todos, state.visibilityFilter)
    15. }
    16. }
    1. const mapDispatchToProps = dispatch => {
    2. return {
    3. onTodoClick: id => {
    4. dispatch(toggleTodo(id))
    5. }
    6. }
    7. }

    Finally, we create the VisibleTodoList by calling connect() and passing these two functions:

    1. import { connect } from 'react-redux'
    2. const VisibleTodoList = connect(
    3. mapStateToProps,
    4. mapDispatchToProps
    5. )(TodoList)
    6. export default VisibleTodoList

    These are the basics of the React Redux API, but there are a few shortcuts and power options so we encourage you to check out in detail. In case you are worried about mapStateToProps creating new objects too often, you might want to learn about computing derived data with .

    Find the rest of the container components defined below:

    containers/VisibleTodoList.js

    1. import { connect } from 'react-redux'
    2. import { toggleTodo } from '../actions'
    3. import TodoList from '../components/TodoList'
    4. const getVisibleTodos = (todos, filter) => {
    5. return todos
    6. case 'SHOW_COMPLETED':
    7. return todos.filter(t => t.completed)
    8. case 'SHOW_ACTIVE':
    9. return todos.filter(t => !t.completed)
    10. }
    11. }
    12. const mapStateToProps = state => {
    13. return {
    14. todos: getVisibleTodos(state.todos, state.visibilityFilter)
    15. }
    16. }
    17. const mapDispatchToProps = dispatch => {
    18. return {
    19. onTodoClick: id => {
    20. dispatch(toggleTodo(id))
    21. }
    22. }
    23. }
    24. const VisibleTodoList = connect(
    25. mapStateToProps,
    26. mapDispatchToProps
    27. )(TodoList)
    28. export default VisibleTodoList

    Implementing Other Components

    containers/AddTodo.js

    Recall as mentioned previously, both the presentation and logic for the AddTodo component are mixed into a single definition.

    1. import React from 'react'
    2. import { connect } from 'react-redux'
    3. import { addTodo } from '../actions'
    4. let AddTodo = ({ dispatch }) => {
    5. let input
    6. return (
    7. <div>
    8. <form
    9. onSubmit={e => {
    10. e.preventDefault()
    11. if (!input.value.trim()) {
    12. return
    13. }
    14. dispatch(addTodo(input.value))
    15. input.value = ''
    16. }}
    17. >
    18. <input
    19. ref={node => {
    20. input = node
    21. }}
    22. />
    23. <button type="submit">Add Todo</button>
    24. </form>
    25. </div>
    26. )
    27. }
    28. AddTodo = connect()(AddTodo)
    29. export default AddTodo

    If you are unfamiliar with the ref attribute, please read this to familiarize yourself with the recommended use of this attribute.

    components/App.js

    1. import React from 'react'
    2. import Footer from './Footer'
    3. import AddTodo from '../containers/AddTodo'
    4. import VisibleTodoList from '../containers/VisibleTodoList'
    5. const App = () => (
    6. <div>
    7. <AddTodo />
    8. <VisibleTodoList />
    9. <Footer />
    10. </div>
    11. )
    12. export default App

    All container components need access to the Redux store so they can subscribe to it. One option would be to pass it as a prop to every container component. However it gets tedious, as you have to wire store even through presentational components just because they happen to render a container deep in the component tree.

    The option we recommend is to use a special React Redux component called to magically make the store available to all container components in the application without passing it explicitly. You only need to use it once when you render the root component:

    index.js

    Next Steps

    Read the to better internalize the knowledge you have gained.Then, head straight to the advanced tutorial to learn how to handle network requests and routing!