note

Defining a store (createStore)

import { createStore } from 'redux';

function reducer(state = initialState, action) {
  switch (action.type) {
    'INCREMENT':
      return {
        count: state.count + 1
      }
    'DECREMENT':
      return {
        count: state.count -1
      }
    default:
      return state;
  }
}

const store = createStore(reducer);

connect

Replace direct usage of your Component with this;

import { connect } from 'react-redux';

// this function will define how the current component will use the global state
function mapStateToProps(state) {
  return {
    x: state.x,
  }
}

class Component extends React.Component {
  increment = () => {
    this.props.dispatch({ type: 'INCREMENT' })
  }
  decrement = () => {
    this.props.dispatch({ type: 'DECREMENT' })
  }
  render() {
    return {
      <div>
        <button onClick={this.decrement}>-<button>
        <span>{this.props.x}</span>
        <button onClick={this.increment}>+</button>
      </div>
    }
  }
}

export connect(mapStateToProps)(Component);

Provider

To do this, we need to provide the state to the whole application. Like the following

import { Provider } from 'react-redux';

...
const App = () => {
  <Provider store={store}>
    <Component />
  </Provider>
}

store is the one from output of the createStore method.

About me

Stuff I do with my brain, my fingers and an editor:

(Front-end) development - typescript, Vue, React, svelte(kit) web architectures web performance API design pragmatic SEO security Accessibility (A11y) front-end dev recruitment and probably more...

Feel free to , check out my open source projects, or just read the things I write on this site.