useState, useEffect, fetch를 중점적으로 공부하자!
useReducer 몰라도 된다!!
//interval 실행
id = setInterval(() => {
console.log(1);
}, 1000);
// 끌때
clearInterval(id)
useEffect의 첫번째 파라미터는 콜백함수, 콜백함수의 리턴값은 함수고, 그 함수는 컴포넌트가 제거될 때 호출된다.
a = () => {
let id = 1;
return () => {
console.log(id);
}
}
a()//() => { console.log(id); }
b = a()
import { blue, grey } from "@mui/material/colors";
const darkThema = createTheme({
palette: {
primary: grey,
},
});
<ThemeProvider theme={darkThema}>
<Counter4UseEffect />
</ThemeProvider>
// 기본 구조
import React from "react";
export function ContextAPI() {
return (
<div className="layout">
<h1>Context api</h1>
<button>+</button>
<ContextAPISub />
</div>
);
}
function ContextAPISub() {
return (
<div className="layout">
<h1>sub</h1>
<button>+</button>
</div>
);
}
const [변경될 값, 바꾸라고 하는 명령] = useReducer(값을 변경하는 함수, 기본값);
function 값을변경하는함수(oldCount:number, action:string):number{
if(action === "UP"){
return oldCount + 1;
} else if(action === "DOWN"){
return oldCount - 1;
} else if(action === "RESET"){
return 0;
}
}
오오ㅗ옹 개신기해!!
function MyUseReduce() {
// const [count, setCount] = useState(0);
function countReducer(oldCount: number, action: string): number {
console.log(oldCount, action);
return oldCount;
}
const [count, countDispatch] = useReducer(countReducer, 10);
return (
<div className="layout">
<h1>useReduce</h1>
<button
onClick={() => {
// setCount(count + 1);
countDispatch("UP");
}}
>
+
</button>
<button
onClick={() => {
// setCount(count - 1);
countDispatch("DOWN");
}}
>
-
</button>
<button
onClick={() => {
// setCount(0);
countDispatch("RESET");
}}
>
0
</button>
{count}
</div>
);
}
function MyUseReduce() {
// const [count, setCount] = useState(0);
function countReducer(oldCount: number, action: string): number {
console.log(oldCount, action);
if (action === "UP") {
return oldCount + 1;
} else if (action === "DOWN") {
return oldCount - 1;
} else if (action === "RESET") {
return 0;
}
return oldCount;
}
const [count, countDispatch] = useReducer(countReducer, 10);
return (
<div className="layout">
<h1>useReduce</h1>
<button
onClick={() => {
// setCount(count + 1);
countDispatch("UP");
}}
>
+
</button>
<button
onClick={() => {
// setCount(count - 1);
countDispatch("DOWN");
}}
>
-
</button>
<button
onClick={() => {
// setCount(0);
countDispatch("RESET");
}}
>
0
</button>
{count}
</div>
);
}
출처 : 엘리스 아카데미