Context API
import { useContext, useState } from "react";
import { createContext } from "react";
const ThemeContext = createContext("light");
export const ThemeProvier = ({ children }) => {
const [theme, setTheme] = useState("light");
const handleToggle = () => {
setTheme((pre) => (pre === "light" ? "dark" : "light"));
};
return (
<ThemeContext.Provider value={{ theme, onToggle: handleToggle }}>
{children}
</ThemeContext.Provider>
);
};
export const ThemeComponent = () => {
const { theme, onToggle } = useContext(ThemeContext);
return (
<div>
<p>{theme}</p>
<button onClick={onToggle}>
{theme === "light" ? "다크모드" : "라이트 모드"}
</button>
</div>
);
};
import { ThemeProvier, ThemeComponent } from "./Theme";
function App() {
return (
<div>
<ThemeProvier>
<ThemeComponent></ThemeComponent>
</ThemeProvier>
</div>
);
}
export default App;
useRef
- 특정 요소를 조작할 때 값을 저장하지만 랜더링이 다시 필요하지 않을 때 사용한다.
function FocusInput() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus input</button>
</div>
);
}
function App() {
const [seconds, setSecond] = useState(0);
const timeRef = useRef(null);
const handleStart = () => {
if (timeRef.current) return;
timeRef.current = setInterval(() => {
setSecond((pre) => pre + 1);
}, 1000);
};
const handleEnd = () => {
clearInterval(timeRef.current);
timeRef.current = null;
};
return (
<div>
<h1>timer: {seconds}</h1>
<button onClick={handleStart}>Start</button>
<button onClick={handleEnd}>End</button>
<FocusInput />
</div>
);
}
export default App;
useEffect
- return에 clean up 함수를 넣어서 컴포넌트가 언마운트될때 메모리 누수 방지를 할 수 있다.