React exposes two hooks for managing state: useState
and useReducer
. Both of these hooks are used to manage state in a component. The difference between the two is that useState
is a hook that is better suited to manage a single piece of state, while useReducer
is a hook that manages more complex state. Let’s take a look at how we can use useState
to manage state in a component
import { useState } from "react";
const MyComponent = () => {
const [state, setState] = useState({
count: 0,
name: "Tejumma",
age: 30,
});
return (
<div>
<p>Count: {state.count}</p>
<p>Name: {state.name}</p>
<p>Age: {state.age}</p>
<button onClick={() => setState({ ...state, count: state.count + 1 })}>
Increment
</button>
</div>
);
};
Fun fact: useState
uses useReducer
internally. You can think of useState
as a higher-level abstraction of useReducer
. In fact, one can reimplement useState
with useReducer
if they so wish!
import { useReducer } from "react";
const initialState = {
count: 0,
name: "Tejumma",
age: 30,
};
const reducer = (state, action) => {
switch (action.type) {
case "increment":
return { ...state, count: state.count + 1 };
default:
return state;
}
};
const MyComponent = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<p>Name: {state.name}</p>
<p>Age: {state.age}</p>
<button onClick={() => dispatch({ type: "increment" })}>Increment</button>
</div>
);
};
ss