diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md index 3fe42def1..ac49c3127 100644 --- a/docs/GettingStarted.md +++ b/docs/GettingStarted.md @@ -1,9 +1,6 @@ # Getting Started -[React-Redux](https://github.com/reduxjs/react-redux) is the official [React](https://reactjs.org/) binding for [Redux](https://redux.js.org/). -Redux has no knowledge of React. -You may create your Redux app using other UI rendering frameworks, or not using any frameworks at all. -It lets your React components read data and dispatch actions from and to a Redux store. +[React-Redux](https://github.com/reduxjs/react-redux) is the official [React](https://reactjs.org/) binding for [Redux](https://redux.js.org/). ​​It lets your React components read data from a Redux store, and dispatch actions to the store to update data. ## Installation @@ -23,7 +20,7 @@ yarn add react-redux ## `` and `connect` -**React-Redux provides the `` that serves the Redux store of your app:** +React-Redux consists of two main pieces. The first is a component called ``, which makes the Redux store available to the rest of your app: ```js import React from "react"; @@ -43,7 +40,7 @@ ReactDOM.render( ); ``` -**React-Redux also provides the `connect()` function to help you connect a React component to the Redux `store`.** +The second piece is a function called `connect()`, which encapsulates the process of talking to the store. It enables you to: @@ -54,7 +51,9 @@ Correspondingly, the `connect` function takes two arguments, both optional: - `mapStateToProps`: called every time the store state changes. It receives the entire store state, and should return an object of data this component needs. -- `mapDispatchToProps`: called once on component creation. It receives the dispatch method, and should return an object full of functions that use dispatch. This param _can_ be an object as well. And it will be how you normally use it. If `connect` receives an object full of action creators for this param, it binds `dispatch` for you automatically. +- `mapDispatchToProps`: this parameter can either be a function, or an object. + - If it’s a function, it will be called once on component creation. It will receive `dispatch` as an argument, and should return an object full of functions that use `dispatch` to dispatch actions. + - If it’s an object full of action creators, each action creator will be turned into a prop function that automatically dispatches its action when called. **Note**: We recommend using this “object shorthand” form. Normally, you’ll call `connect` in this way: @@ -84,7 +83,7 @@ connect( ## A Todo List Example -We show a step-by-step example by creating a todo list app using React-Redux. +To see this in practice, we’ll show a step-by-step example by creating a todo list app using React-Redux. **Jump to** @@ -109,7 +108,7 @@ We have implemented our React UI components as follows: - It accepts an `activeFilter` prop from the parent that indicates which filter is currently selected by the user. An active filter is rendered with an underscore. - It dispatches the `setFilter` action to update the selected filter. - `constants` holds the constants data for our app. -- And finally `style.css` is the stylesheet, and `index` renders our app to the DOM. +- And finally `index` renders our app to the DOM. You may check out the sourcecode below or check out this CodeSandbox: [Todo App UI Only](https://codesandbox.io/s/mo7p88po0j). @@ -124,10 +123,9 @@ You may check out the sourcecode below or check out this CodeSandbox: [Todo App │ ├── TodoList.js │ ├── Todo.js │ └── VisibilityFilters.js -├── index.js ├── TodoApp.js ├── constants.js -└── style.css +└── index.js ``` ```jsx @@ -136,7 +134,6 @@ import React from "react"; import AddTodo from "./components/AddTodo"; import TodoList from "./components/TodoList"; import VisibilityFilters from "./components/VisibilityFilters"; -import "./styles.css"; export default function TodoApp() { return ( @@ -265,17 +262,6 @@ const VisibilityFilters = ({ activeFilter }) => { export default VisibilityFilters; ``` -```jsx -// index.js -import React from "react"; -import ReactDOM from "react-dom"; - -import TodoApp from "./TodoApp"; - -const rootElement = document.getElementById("root"); -ReactDOM.render(, rootElement); -``` - ```JavaScript // constants.js export const VISIBILITY_FILTERS = { @@ -285,45 +271,15 @@ export const VISIBILITY_FILTERS = { }; ``` -```css -/** styles.css**/ - -.todo-app { - font-family: sans-serif; -} - -/** add todo **/ -.add-todo { - margin-left: 0.5rem; -} - -/** todo list **/ -.todo-list { - margin-top: 1rem; - text-align: left; - list-style: none; -} +```jsx +// index.js +import React from "react"; +import ReactDOM from "react-dom"; -/** todo item **/ -.todo-item { - font-family: monospace; - cursor: pointer; - line-height: 1.5; -} -.todo-item__text--completed { - text-decoration: line-through; - color: lightgray; -} +import TodoApp from "./TodoApp"; -/** visibility filters **/ -.filter { - padding: 0.3rem 0; - margin: 0 0.3rem; - cursor: pointer; -} -.filter--active { - border-bottom: 1px solid black; -} +const rootElement = document.getElementById("root"); +ReactDOM.render(, rootElement); ``` @@ -333,11 +289,11 @@ export const VISIBILITY_FILTERS = { We have also created the Redux as follows. To learn about designing your Redux store, [the official Redux docs](https://redux.js.org/basics) has an excellent guide. - Store - - `todos`: A normalized reducer of todos. It contains a `byIds` map of all todos and a `allIds` that contains the list of all ids. + - `todos`: A normalized reducer of todos. It contains a `byIds` map of all todos and a `allIds` that contains the list of all ids. - `visibilityFilters`: A simple string `all`, `completed`, or `incomplete`. - Action Creators - - `addTodo` creates the action to add todo’s. It takes a single string variable `content` and returns an `ADD_TODO` action with `payload` containing a self-incremented `id` and `content` - - `toggleTodo` creates the action to toggle todo’s. It takes a single number variable `id` and returns a `TOGGLE_TODO` action with `payload` containing `id` only + - `addTodo` creates the action to add todos. It takes a single string variable `content` and returns an `ADD_TODO` action with `payload` containing a self-incremented `id` and `content` + - `toggleTodo` creates the action to toggle todos. It takes a single number variable `id` and returns a `TOGGLE_TODO` action with `payload` containing `id` only - `setFilter` creates the action to set the app’s active filter. It takes a single string variable `filter` and returns a `SET_FILTER` action with `payload` containing the `filter` itself - Reducers - The `todos` reducer @@ -349,7 +305,7 @@ We have also created the Redux as follows. To learn about designing your Redux s - Selectors - `getTodoList` returns the `allIds` list from the `todos` store - `getTodoById` finds the todo in the store given by `id` - - `getTodos` is slightly more complex. It takes all the `id`s from `allIds`, finds each todo in `byIds`, and returns the final array of todo’s. + - `getTodos` is slightly more complex. It takes all the `id`s from `allIds`, finds each todo in `byIds`, and returns the final array of todos - `getTodosByVisibilityFilter` filters the todos according to the visibility filter Once again you may expand the code below or check out this CodeSandbox here [Todo App (UI + Unconnected Redux)](https://codesandbox.io/s/6vwyqrpqk3). @@ -479,13 +435,13 @@ export const setFilter = filter => ({ type: SET_FILTER, payload: { filter } }); // redux/selectors.js import { VISIBILITY_FILTERS } from "../constants"; +export const getTodosState = store => store.todos; + export const getTodoList = store => - store && store.todos ? store.todos.allIds : []; + getTodosState(store) ? getTodosState(store).allIds : []; export const getTodoById = (store, id) => - store && store.todos && store.todos.byIds - ? { ...store.todos.byIds[id], id } - : {}; + getTodoState(store) ? { ...getTodosState(store).byIds[id], id } : {}; /** * example of a slightly more complex selector @@ -521,7 +477,7 @@ We now show how to connect this store to our app using React-Redux. ### Providing the Store -First we need to make the `store` available to our app. To do this, we wrap our app with the `` api provided by React-Redux. +First we need to make the `store` available to our app. To do this, we wrap our app with the `` API provided by React-Redux. ```jsx // index.js @@ -541,7 +497,7 @@ ReactDOM.render( ); ``` -Notice how our `` is now wrapped with the `` with `store` passed in as a prop. The `store` object has a few methods that do their magic. But we won’t go into them, yet. We’ll explain them later in the “whys and hows” section. +Notice how our `` is now wrapped with the `` with `store` passed in as a prop. ![](https://i.imgur.com/LV0XvwA.png) @@ -549,11 +505,7 @@ Notice how our `` is now wrapped with the `` with `store` Our components need to read values from the Redux store (and re-read the values when the store updates). They also need to dispatch actions to trigger updates. -`connect` takes in two parameters. -The first one allows you to define which pieces of data from the store are needed by this component. -The second one allows you to indicate which actions that component might dispatch. By convention, they are called `mapStateToProps` and `mapDispatchToProps`, respectively. -The return of this call is another function that accepts the component on a second call. -This is an example of a pattern called [_higher order components_](https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e). +`connect` takes in two parameters. The first one allows you to define which pieces of data from the store are needed by this component. The second one allows you to indicate which actions that component might dispatch. By convention, they are called `mapStateToProps` and `mapDispatchToProps`, respectively. The return of this call is another function that accepts the component on a second call. This is an example of a pattern called [_higher order components_](https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e). Let’s work on `` first. It needs to trigger changes to the `store` to add new todos. Therefore, it needs to be able to `dispatch` actions to the store. Here’s how we do it. @@ -574,6 +526,7 @@ export const addTodo = content => ({ // ... other actions ``` + By passing it to `connect`, our component receives it as a prop, and it will automatically dispatch the action when it’s called. ```jsx @@ -636,16 +589,19 @@ export default connect( null, { addTodo } )(AddTodo); - ``` -Now our `` is connected to the store. It _should_ dispatch an action to change the store upon the user’s add todo interaction. But we are unable to see it before our `` is also connected to the store. So let’s do it now. +Now our `` is connected to the store. When we add a todo it would dispatch an action to change the store. We are not seeing it in the app because the other components are not connected yet. If you have the Redux DevTools Extension hooked up, you should see the action being dispatched: + +![](https://i.imgur.com/kHvkqhI.png) + +You should also see that the store has changed accordingly: + +![](https://i.imgur.com/yx27RVC.png) The `` component is responsible for rendering the list of todos. Therefore, it needs to read data from the store. We enable it by calling `connect` with the `mapStateToProps` parameter, a function describing which part of the data we need from the store. -Our `` component takes the todo item as props. We have this information from the `byIds` field of the `todos`. -However, we also need the information from the `allIds` field of the store indicating which todos and in what order they should be rendered. -Our `mapStateToProps` function may look like this: +Our `` component takes the todo item as props. We have this information from the `byIds` field of the `todos`. However, we also need the information from the `allIds` field of the store indicating which todos and in what order they should be rendered. Our `mapStateToProps` function may look like this: ```jsx // components/TodoList.js @@ -658,7 +614,7 @@ const TodoList = // ... UI component implementation const mapStateToProps = state => { const { byIds, allIds } = state.todos || {}; const todos = - allIds && state.todos.allIds.length + allIds && allIds.length ? allIds.map(id => (byIds ? { ...byIds[id], id } : null)) : null; return { todos }; @@ -672,13 +628,13 @@ Luckily we have a selector that does exactly this. We may simply import the sele ```jsx // redux/selectors.js +export const getTodosState = store => store.todos; + export const getTodoList = store => - store && store.todos ? store.todos.allIds : []; + getTodosState(store) ? getTodosState(store).allIds : []; export const getTodoById = (store, id) => - store && store.todos && store.todos.byIds - ? { ...store.todos.byIds[id], id } - : {}; + getTodoState(store) ? { ...getTodosState(store).byIds[id], id } : {}; /** * example of a slightly more complex selector @@ -700,30 +656,29 @@ const TodoList = // ... UI component implementation export default connect(state => ({ todos: getTodos(state) }))(TodoList); ``` -So that provides with a motivation to write selector functions for complex computation. You may further optimize by using [Reselect](https://github.com/reduxjs/reselect). +So that provides with a motivation to write selector functions for complex computation. You may further optimize the performance by using [Reselect](https://github.com/reduxjs/reselect) to write “memoized” selectors that can skip unnecessary work. See [this Redux’s docs page on Computing Derived Data](https://redux.js.org/recipes/computingderiveddata#sharing-selectors-across-multiple-components) for more information on using selectors. -Now that our `` is connected to the store. It should receive the list of todos, map over them, and pass each todo to the `` component. `` will in turn render them to the screen. -Now try adding a todo. It should come up on our todo list! +Now that our `` is connected to the store. It should receive the list of todos, map over them, and pass each todo to the `` component. `` will in turn render them to the screen. Now try adding a todo. It should come up on our todo list! ![](https://i.imgur.com/N68xvrG.png) -We will connect more components. -Before we do this, let’s pause and learn a bit more about `connect` first. +We will connect more components. Before we do this, let’s pause and learn a bit more about `connect` first. ### Common ways of calling `connect` Depending on what kind of components you are working with, there are different ways of calling `connect` , with the most common ones summarized as below: -| | Do Not Subscribe to Store | Subscribe to Store | -| ----------------------------- | ------------------------------------------------------------ | --------------------------------------------------------- | -| Do Not Inject Action Creators | `connect()(Component)` _Component will receive_ `*dispatch*` | `connect(mapStateToProps)(Component)` | -| Inject Action Creators | `connect(null, mapDispatchToProps)(Component)` | `connect(mapStateToProps, mapDispatchToProps)(Component)` | +| | Do Not Subscribe to the Store | Subscribe to the Store | +| ----------------------------- | ---------------------------------------------- | --------------------------------------------------------- | +| Do Not Inject Action Creators | `connect()(Component)` | `connect(mapStateToProps)(Component)` | +| Inject Action Creators | `connect(null, mapDispatchToProps)(Component)` | `connect(mapStateToProps, mapDispatchToProps)(Component)` | #### Do not subscribe to the store and do not inject action creators -Not providing neither `mapStateToProps` nor `mapDispatchToProps`, your component will: -- _not_ re-render on store changes -- receive `props.dispatch` that you may use to manually dispatch action creators. +If you call `connect` without providing any arguments, your component will: + +- _not_ re-render when the store changes +- receive `props.dispatch` that you may use to manually dispatch action ```jsx // ... Component @@ -732,10 +687,10 @@ export default connect()(Component); // Component will receive `dispatch` (just #### Subscribe to the store and do not inject action creators -Providing `mapStateToProps` and not providing `mapDispatchToProps`, your component will: +If you call `connect` with only `mapStateToProps`, your component will: -- subscribe to the slice of store returned by `mapStateToProps` and re-render when that part of store changes only -- receive `props.dispatch` that you may use to manually dispatch action creators +- subscribe to the values that `mapStateToProps` extracts from the store, and re-render only when those values have changed +- receive `props.dispatch` that you may use to manually dispatch action ```jsx // ... Component @@ -745,9 +700,10 @@ export default connect(mapStateToProps)(Component); #### Do not subscribe to the store and inject action creators -Providing `mapDispatchToProps` and not providing `mapStateToProps`, your component will: +If you call `connect` with only `mapDispatchToProps`, your component will: + - _not_ re-render when the store changes -- receive each of the action creators you inject with `mapDispatchToProps` as props and will automatically dispatch them upon being called. +- receive each of the action creators you inject with `mapDispatchToProps` as props and automatically dispatch the actions upon being called ```jsx import { addTodo } from "./actionCreators"; @@ -760,18 +716,22 @@ export default connect( #### Subscribe to the store and inject action creators -Providing `connect` with both `mapStateToProps` and `mapDispatchToProps`, your component will: -- subscribe to the slice of store returned by `mapStateToProps` and re-render when that part of store changes only -- receive all of the action creators you inject with `mapDispatchToProps` as props and will automatically dispatch them upon being called. +If you call `connect` with both `mapStateToProps` and `mapDispatchToProps`, your component will: + +- subscribe to the values that `mapStateToProps` extracts from the store, and re-render only when those values have changed +- receive all of the action creators you inject with `mapDispatchToProps` as props and automatically dispatch the actions upon being called. ```jsx -import * as actionCreators from './actionCreators'; +import * as actionCreators from "./actionCreators"; // ... Component const mapStateToProps = state => state.partOfState; -export default connect(mapStateToProps, actionCreators)(Component); +export default connect( + mapStateToProps, + actionCreators +)(Component); ``` -These four cases cover the most basic usages of `connect`. To read more about `connect`, continue reading our [API section](./api.md) that explains it in more detail. +These four cases cover the most basic usages of `connect`. To read more about `connect`, continue reading our [API section](./api.md) that explains it in more detail. @@ -800,11 +760,6 @@ Now our todo’s can be toggled complete. We’re almost there! ![](https://i.imgur.com/4UBXYtj.png) -There are some common practices in implementing React applications. One such example is to separate components into _presentational_ and _container_ components. -You use this pattern when you realize that some of your components are more intelligent than others. -And you want to organize your program such that certain components are mainly responsible for connecting to the store (the "containers"), while some other components are mainly responsible for rendering whichever data they receive (the "presentational" components). -[This article](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0) by Dan Abramov has a nice introduction. - Finally, let’s implement our `VisibilityFilters` feature. The `` component needs to be able to read from the store which filter is currently active, and dispatch actions to the store. Therefore, we need to pass both a `mapStateToProps` and `mapDispatchToProps`. The `mapStateToProps` here can be a simple accessor of the `visibilityFilter` state. And the `mapDispatchToProps` will contain the `setFilter` action creator. @@ -869,10 +824,12 @@ Now we've finished a very simple example of a todo app with React-Redux. All our ![](https://i.imgur.com/ONqer2R.png) ## Links + - [Usage with React](https://redux.js.org/basics/usagewithreact) - [Using the React-Redux Bindings](https://blog.isquaredsoftware.com/presentations/workshops/redux-fundamentals/react-redux.html) - [Higher Order Components in Depth](https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e) -- [Presentational and Container Components](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0) + +- [Computing Derived Data](https://redux.js.org/recipes/computingderiveddata#sharing-selectors-across-multiple-components) ## Get More Help