Skip to content

Instantly share code, notes, and snippets.

@tunapotur
Last active September 23, 2022 09:51
Show Gist options
  • Save tunapotur/f268303ec0305cff6c29ae10666e4261 to your computer and use it in GitHub Desktop.
Save tunapotur/f268303ec0305cff6c29ae10666e4261 to your computer and use it in GitHub Desktop.
DaveCeddia Hook useReducer example
// https://www.youtube.com/watch?v=sYDFCuZHrqw&list=PL-F_CAUJfW9Xbg5l4PGknlRqur9oT_8Go&index=2
// DaveCeddia Hook useReducer example
import React, { useReducer } from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
const inlineStyle = {
display: "flex",
flexDirection: "column",
justifyContent: "space-around",
alignItems: "center",
height: "90px",
width: "210px",
fontSize: "24px",
margin: "30px",
fontWeight: "bold",
border: "1px solid black",
padding: "10px",
};
const buttons = {
display: "flex",
justifyContent: "space-between",
width: "210px",
};
const button = {
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "90px",
height: "30px",
};
const number = {
display: "flex",
justifyContent: "center",
};
const Count = () => {
const [count, dispatch] = useReducer((state, action) => {
switch (action) {
case "+":
return state + 1;
case "-":
return state - 1;
default:
return state;
}
}, 0);
return (
<div style={inlineStyle}>
<span style={number}>{count}</span>
<div style={buttons}>
<button style={button} onClick={() => dispatch("-")}>
Decrement
</button>
<button style={button} onClick={() => dispatch("+")}>
Increment
</button>
</div>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Count />);
// https://www.youtube.com/watch?v=sYDFCuZHrqw&list=PL-F_CAUJfW9Xbg5l4PGknlRqur9oT_8Go&index=2
// DaveCeddia Hook useReducer more complex example
import React, { useReducer, useRef } from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
const ShoppingList = () => {
const inputRef = useRef();
const [items, dispatch] = useReducer((state, action) => {
switch (action.type) {
case "add":
return [...state, { id: Math.random().toString(), name: action.name }];
case "remove":
return state.filter((_, index) => index !== action.index);
case "clear":
return [];
default:
return state;
}
}, []);
const handleSubmit = (event) => {
event.preventDefault();
dispatch({
type: "add",
name: inputRef.current.value,
});
inputRef.current.value = "";
};
return (
<>
<form onSubmit={handleSubmit}>
<input ref={inputRef} />
</form>
<button onClick={() => dispatch({ type: "clear" })}>Clear</button>
<ul>
{items.map((item, index) => (
<li key={item.id}>
{item.name}{" "}
<button onClick={() => dispatch({ type: "remove", index })}>
X
</button>
</li>
))}
</ul>
</>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<ShoppingList />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment