Last active
February 2, 2020 19:51
-
-
Save rolandpeelen/622d47dbdf426f4e889f280707c0b0f6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://jesseduffield.com/in-react-the-wrong-abstraction-kills-efficiency/ | |
| // App.js | |
| import React, { Component } from "react"; | |
| import { createStore } from "redux"; | |
| import { Provider } from "react-redux"; | |
| import CounterSection from "./CounterSection"; | |
| import "./App.css"; | |
| function counter(state = 0, action) { | |
| switch (action.type) { | |
| case "MULTIPLY": | |
| return state * parseInt(action.data); | |
| case "PLUS": | |
| return state + parseInt(action.data); | |
| case "RESET": | |
| return 0; | |
| default: | |
| return state; | |
| } | |
| } | |
| let store = createStore(counter); | |
| class App extends Component { | |
| render() { | |
| return ( | |
| <Provider store={store}> | |
| <div className="App"> | |
| <h1>Counter Culture, The #1 Counter App</h1> | |
| <CounterSection /> | |
| </div> | |
| </Provider> | |
| ); | |
| } | |
| } | |
| // CounterSection.js | |
| import React, { Component } from "react"; | |
| import { useDispatch, useSelector } from "react-redux"; | |
| const CounterButton = ({ title, onClick }) => ( | |
| <button className="counter-button" onClick={onClick}> | |
| {title} | |
| </button> | |
| ); | |
| const CounterSection = () => { | |
| const dispatch = useDispatch(); | |
| const counter = useSelector(state => state); | |
| const [inputValue, setInputValue] = useState(0); | |
| const dispatcher = type => data => _ => dispatch(type, data); | |
| const plus = dispatcher("ADD"); | |
| const multiply = dispatcher("MULTIPLY"); | |
| const reset = dispatcher("RESET"); | |
| const log = _ => console.log(`current value: ${counter}`); | |
| const buttons = [ | |
| { title: "Increment", action: plus(1) }, | |
| { title: "Decrement", action: plus(-1) }, | |
| { title: "Double", action: multiply(2) }, | |
| { title: "Reset", action: reset(null) }, | |
| { title: "Log", action: log } | |
| ]; | |
| return ( | |
| <div> | |
| <h1>{counter}</h1> | |
| {buttons.map(({ cb, title }) => ( | |
| <CounterButton key={title} onClick={action} title={title} /> | |
| ))} | |
| <input | |
| onChange={e => setInputValue(e.target.value)} | |
| defaultValue={inputValue} | |
| /> | |
| <CounterButton onClick={plus(inputValue)} title="Add"/> | |
| </div> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment