useReducer Hook WIth Example

full-width

import { useReducer, useState } from "react";

const initialState = {
value: 5,
name: "React Toolkit",
};

function reducer(state, action) {
switch (action.type) {
case "Add":
return { ...state, value: state.value + 1 };
case "Remove":
return { ...state, value: state.value - 1 };
case "changeName":
return { ...state, name: action.payload };
default:
return state;
}
}

function App() {
const [changeValue, setChangeValue] = useState("");
const [state, dispatch] = useReducer(reducer, initialState);

const handleSubmit = (e) => {
e.preventDefault();
dispatch({ type: "changeName", payload: changeValue }); // payload is the value that we want to pass to the reducer)
setChangeValue("");
};

return (
<>
<div>
<h2>{state.value}</h2>
<h2>{state.name}</h2>

<button
style={{ marginRight: "5px" }}
onClick={() => dispatch({ type: "Add" })}
>
Add
</button>

<button onClick={() => dispatch({ type: "Remove" })}>Remove</button>

<div>
<br />
<form onSubmit={handleSubmit}>
<label htmlFor="textInput">Enter Your Text</label>
<br />
<input
type="text"
placeholder="Inter Text..."
value={changeValue}
onChange={(e) => setChangeValue(e.target.value)}
/>
<br /> <br />
<button type="submit">Submit</button>
</form>
</div>
</div>
</>
);
}

export default App;