1. useReducer

useReducer is a hook that helps manage state. It's an alternative to useState.

It's useful for handling complex state logic where the next state depends on the previous one.


2. dispatch and reducer

reducer function: This function takes the current state and an action as arguments and returns the new state.

dispatch function: A function you use to pass an action. When you call dispatch(action), React runs your reducer function with the current state and the provided action, and then updates the state with the reducer's return value.


3. Sample Code

import logo from './logo.svg';
import './App.css';
import React, { useReducer } from 'react';
import { useDebugValue, forwardRef, useImperativeHandle, useState, useEffect, useRef, useMemo, useCallback, memo} from 'react';
import Timer from './component/Timer.js';
import Page from './component/Page.jsx'
import {ThemeContext} from './context/ThemeContext.js'

const reducer = (state, action) => {
console.log("reducer called ", state, action)
//reducer function updates state using current state and action
switch(action.type) {
case 'deposit' :
return state+action.payload
case 'withdraw':
return state-action.payload
default:
return state
}
}

function App() {
const [number, setNumber] = useState(0);
const [money, dispatch] = useReducer(reducer, 0); //useReducer takes reducer function and initial value of state

return (
<>
<div>
<h2>useReducer bank, Welcome!</h2>
<p>잔고: {money}</p>
<input
type = 'number'
value = {number}
onChange={(e) => setNumber(parseInt(e.target.value))}
/> //when dispatch is called, reducer update state
<button onClick={() => {dispatch({type: 'deposit', payload: number})}}>DEPOSIT</button>
<button onClick={() => {dispatch({type: 'withdraw', payload: number})}}>WITHDRAW</button>
</div>
</>
)
}

export default App;