An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
December 16, 2022 09:09 am GMT
Original Link: https://dev.to/csituma/usestate-vs-usereducer-with-examples-choose-your-champion-26hi
useState vs useReducer - choose your champion
Below are two ways of implementing a simple counter in a React application:
Here's how to achieve that with useReducer:
import { useReducer } from 'react';const initialState = { count: 0,};const reducer = (state, action) => { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: return state; }};function ParentComponent() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <ChildComponent dispatch={dispatch} /> </div> );}function ChildComponent(props) { return ( <div> <button onClick={() => props.dispatch({ type: "increment" })}> Increment </button> <button onClick={() => props.dispatch({ type: "decrement" })}> Decrement </button> </div> );}
Here's how to achieve that using useState
import { useState } from 'react';function ParentComponent() { const [state, setState] = useState({ count: 0 }); return ( <div> <p>Count: {state.count}</p> <ChildComponent setState={setState} /> </div> );}function ChildComponent(props) { return ( <div> <button onClick={() => props.setState({ count: props.count + 1 })}> Increment </button> <button onClick={() => props.setState({ count: props.count - 1 })}> Decrement </button> </div> );}
Which one are you picking and why?
Original Link: https://dev.to/csituma/usestate-vs-usereducer-with-examples-choose-your-champion-26hi
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To