React - Redux

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

React Redux is a binder for React of the Redux state management.

Two steps:

Advertising

3 - Installation

npm install --save react-redux

4 - API

4.1 - Provider

Provider magically make the store available to all container components in the application without passing it explicitly.

Example:

// Needed when using Jsx
import React from 'react';
// Needed to render the app
import ReactDOM from 'react-dom';
 
// Redux for the storage
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import reducer from './reducer'
 
// Create a store using your reducer (function that handles the action)
const store = createStore(reducer)
 
ReactDOM.render(
    <Provider store={store}>
        <App/>
    </Provider>,
    document.getElementById('root')
);

4.2 - Container component

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. In addition to reading the state, container components can dispatch actions.

4.2.1 - Connect

The React Redux library's connect() function:

  • Connects a React component to a Redux store.
  • Generates container components (no need to subscribe)
  • Provides many useful optimizations to prevent unnecessary re-renders. (no implementation of shouldComponentUpdate)

The connect() function takes as argument:

  • the function mapStateToProps(state, [ownProps]): stateProps.
    • The results of mapStateToProps must be a plain object, which will be merged into the component’s props.
    • the function tells how to transform the current Redux store state (first argument) into the props (return value) you want to pass to the presentational component you are wrapping.
    • the function will subscribe the component to Redux store updates. If you don't want to subscribe to store updates, pass null or undefined
  • the function mapDispatchToProps(dispatch, [ownProps]): dispatchProps that receives the dispatch() method and returns callback props that you want to inject into the presentational component.

Example:

AddTodo = connect()(AddTodo)

or

const mapStateToProps = (state, ownProps) => ({
  active: ownProps.filter === state.visibilityFilter
})
 
const mapDispatchToProps = (dispatch, ownProps) => ({
  onClick: () => {
    dispatch(setVisibilityFilter(ownProps.filter))
  }
})
 
const FilterLink = connect(
  mapStateToProps,
  mapDispatchToProps
)(Link)
Advertising

4.3 - Router

React router and redux. See doc

const Root = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/" component={App} />
    </Router>
  </Provider>
)

5 - Documentation / Reference

web/javascript/react/redux.txt · Last modified: 2019/06/21 09:34 by gerardnico