Skip to content

Instantly share code, notes, and snippets.

@RomainBitard
Created January 25, 2024 06:46
Show Gist options
  • Save RomainBitard/e32a3272d03085b1eff60a38290a4297 to your computer and use it in GitHub Desktop.
Save RomainBitard/e32a3272d03085b1eff60a38290a4297 to your computer and use it in GitHub Desktop.
Redux MVP without npm install
// 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