Skip to content

Instantly share code, notes, and snippets.

@manojsinghnegiwd
Created April 20, 2021 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manojsinghnegiwd/2e0c53cb5202bd00bbf5e3964dec1b20 to your computer and use it in GitHub Desktop.
Save manojsinghnegiwd/2e0c53cb5202bd00bbf5e3964dec1b20 to your computer and use it in GitHub Desktop.
import { render } from "react-dom";
import React, { useState, useCallback } from "react";
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
}
}
function useReducer(reducer, initState) {
const [state, setState] = useState(initState);
const dispatch = useCallback((action) => {
const nextState = reducer(state, action)
setState(nextState)
}, [setState, state])
return [state, dispatch];
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<React.Fragment>
Count: {state.count}
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</React.Fragment>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment