useState ( ) 는 컴포넌트 내에서만 사용사능.
많은 내용이 사용될경우, 컴포넌트가 비대해질 수 있다.
useReducer 사용방법
*const [count(*변수), dispatch(*상태변화촉발함수)] = useReducer( reducer, 0 ) *두개의 인자값 리듀서(상태변화함수), 초기값 ====> component 안에 쓰임
*reducer : 역시 두개의 인자값을 받음 reducer( state, action) ===> state는 상태변화의 최종값, action은 디스패치에 사용된 객체(즉 액션객체)
*dispatch 상태변화의 촉발함수 인자값은 무조건 객체타입
function reducer(state, action) {
switch (action.type) {
case "INCREASE":
return state + action.data;
case "DECREASE":
return state - action.data;
case "INIT":
return 0;
default:
return state;
}
}
function App() {
// const [count, setCount] = useState(0);
// const onIncrease = () => {
// setCount(count + 1);
// };
// const onDecrease = () => {
// setCount(count - 1);
// };
const [count, dispatch] = useReducer(reducer, 0);
return (
<div className="App">
<h4>test component</h4>
<div>
<h1>{count}</h1>
{/* <h1>{count}</h1> */}
</div>
<div>
<button onClick={() => dispatch({ type: "INCREASE", data: 1 })}>
+
</button>
<button onClick={() => dispatch({ type: "DECREASE", data: 1 })}>
-
</button>
<button onClick={() => dispatch({ type: "INIT" })}>0으로 초기화</button>
{/* <button onClick={onIncrease}>+</button>
<button onClick={onDecrease}>-</button> */}
</div>
</div>
);
}
export default App;
'React' 카테고리의 다른 글
230629 useContext( ) (0) | 2023.06.29 |
---|---|
230629 리액트 스타일드 컴포넌트 styled-component / custom Hook / 이벤트 (0) | 2023.06.29 |
230628 아이디/로그인 리액트 만들기, 라우터 (0) | 2023.06.28 |
230615 CountApp 만들기 (0) | 2023.06.15 |
230615 리액트 - useRef (0) | 2023.06.15 |