Created
January 25, 2024 06:46
-
-
Save RomainBitard/e32a3272d03085b1eff60a38290a4297 to your computer and use it in GitHub Desktop.
Redux MVP without npm install
This file contains 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
// idea from https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367 | |
import './App.css'; | |
import React, {useState} from "react"; | |
interface ActionType { | |
type: string; | |
} | |
function CounterReducer(state = {value: 0}, action: ActionType = {type: ""}) { | |
switch (action.type) { | |
case 'INCREMENT': | |
return {value: state.value + 1} | |
case 'DECREMENT': | |
return {value: state.value - 1} | |
default: | |
return state | |
} | |
} | |
function Counter() { | |
const [state, setState] = useState(CounterReducer()) | |
function dispatch(action: ActionType) { | |
setState(prevState => CounterReducer(prevState, action)) | |
} | |
function increment() { | |
dispatch({type: "INCREMENT"}) | |
} | |
function decrement() { | |
dispatch({type: "DECREMENT"}) | |
} | |
return <div> | |
{state.value} | |
<button onClick={increment}>+</button> | |
<button onClick={decrement}>-</button> | |
</div> | |
} | |
function App() { | |
return <Counter/> | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment