Skip to content
Permalink
Browse files

React Hooks with Flux

  • Loading branch information...
dachi023 committed Feb 25, 2019
1 parent 0f5ebfd commit 2c4fe318812ddda722790e74367ce02864ee4c00
@@ -1,28 +1,18 @@
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import React, { useReducer } from 'react'
import Counter from './Counter'
import CounterContext from './contexts/CounterContext'
import CounterReducer from './reducers/CounterReducer'
import './App.css'

class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default function App() {
const [state, dispatch] = useReducer(CounterReducer, { count: 0 })
return (
<div className="App">
<header className="App-header">
<CounterContext.Provider value={{ ...state, dispatch }}>
<Counter />
</CounterContext.Provider>
</header>
</div>
)
}

export default App;
@@ -0,0 +1,14 @@
import React, { useContext } from 'react'
import CounterContext from './contexts/CounterContext'
import { increment, decrement } from './actions/CounterActions'

export default function Counter() {
const { count, dispatch } = useContext(CounterContext)
return (
<>
<h2>{count}</h2>
<button onClick={() => increment(dispatch)}>Increment</button>
<button onClick={() => decrement(dispatch)}>Decrement</button>
</>
)
}
@@ -0,0 +1,13 @@
export function increment(dispatch) {
dispatch({
type: 'increment',
payload: {}
})
}

export function decrement(dispatch) {
dispatch({
type: 'decrement',
payload: {}
})
}
@@ -0,0 +1,6 @@
import { createContext } from 'react'

export default createContext({
count: 0,
dispatch: null
})
@@ -0,0 +1,10 @@
export default function CounterReducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 }
case 'decrement':
return { count: state.count - 1 }
default:
return state
}
}

0 comments on commit 2c4fe31

Please sign in to comment.
You can’t perform that action at this time.