Skip to content

ricca509/redux-no-redux

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 

Repository files navigation

What is this?

A WIP, nothing really.

What you have here is just an exercise to replace Redux and React-redux with React Context and hooks (useReducer, useContext).

It shows that it is somehow possible and doesn't require too much effort, although given the availability of the new tools above, I believe better patterns can be developed, whithout packing them into a redux-like library.

API

It is not nearly as powerful as those libraries, read on to see what you can do with it:

connect()

function connect(mapStateToProps?, mapDispatchToProps?)

The connect function takes only two parameters.

mapStateToProps?: (state, ownProps) => Object

mapDispatchToProps?: (dispatch, ownProps) => Object

mapDispatchToProps has to be a function.

useStore()

function useStore(reducer, initialState?)

There is no combineReducers at the moment.

Example use

import React from "react";
import ReactDOM from "react-dom";
import { ContextProvider, useStore, connect } from "./redux-no-redux";

const initialState = { count: 0 };

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "INCREASE":
      return { ...state, count: state.count + 1 };
    case "DECREASE":
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};

const increase = () => ({
  type: "INCREASE"
});

const decrease = () => ({
  type: "DECREASE"
});

const Counter = ({ count, onIncrease, onDecrease }) => {
  return (
    <div>
      <span>{count}</span>
      <button onClick={onIncrease}>+</button>
      <button onClick={onDecrease}>-</button>
    </div>
  );
};

const mapStateToProps = state => ({
  count: state.count
});

const mapDispatchToProps = dispatch => ({
  onIncrease: () => dispatch(increase()),
  onDecrease: () => dispatch(decrease())
});

const CounterHOC = connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter);

const App = () => {
  const store = useStore(reducer, initialState);

  return (
    <ContextProvider value={store}>
      <CounterHOC />
    </ContextProvider>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

About

An implementation of Redux and React-redux using React Context and hooks - just for fun

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published