Redux can be used with any view library.

npm install react-redux
import { Provider, connect } from 'react-redux' 

<Provider/>

Makes the Redux store available to the connect() calls in the component hierarchy below. Normally, you can’t use connect() without wrapping a parent or ancestor component in <Provider>.

import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { createStore } from 'redux';

import MyRootComponent from './MyRootComponent';

const store = createStore((state, action) => ({}));  

ReactDOM.render(
  <Provider store={store}>
    <MyRootComponent />
  </Provider>,
  rootEl
)

connect()

Connects a React component to a Redux store. It does not modify the component class passed to it; instead, it returns a new, connected component class for you to use.

import React from 'react';
import { connect } from 'react-redux';
import { addTodo } from '../actions';

class App extends React.Component {
    render() {
        console.log(this.props.todos);
        console.log(this.props.addTodo);

        return <h1>Hello!</h1>
    }
}

const mapStateToProps = state => ({ todos: state.todos });
const mapDispatchToProps = dispatch => ({ addTodo: todo => dispatch(addTodo(todo)) })

export default connect(mapStateToProps, mapDispatchToProps)(App);

mapStateToProps()

Tells react-redux how to map redux state to component props. If redux state isn't needed any falsy value should be passed but null is preferable.

connect(null, mapDispatchToProps)(App)
import React from 'react';
import { connect } from 'react-redux';

class App extends React.Component {};

export default connect(
    state => ({
        todos: state.todos,
        filter: state.filter,
    })
)(App)

mapDispatchToProps()

Tells react-redux how to map actions to component props. If actions aren't needed it could be omitted.

connect(mapStateToProps)(App)
import React from 'react'
import { connect } from 'react-redux';
import { addTodo, removeTodo } from '../actions';

class App extends React.Component {}

export default connect(
    state => state,
    dispatch => ({
        addTodo: todo => dispatch(addTodo()),
        removeTodo: todo => dispatch(removeTodo()),
    });
)(App);

If actions names is same as props names shortcut could be used.

import React from 'react'
import { connect } from 'react-redux';
import { addTodo, removeTodo } from '../actions';

class App extends React.Component {}

// produces same result as above
export default connect(
    state => state,
    { addTodo, removeTodo },
)(App);

react-redux

By Nikita Rudy

react-redux

  • 362