[250916] TIL
Today I Learned (2025-09-16)
React DevTools
- ๋ธ๋ผ์ฐ์ ํ์ฅ ํ๋ก๊ทธ๋จ
Tab.displayName = 'Tab'
- HOC(๊ณ ์ฐจ ์ปดํฌ๋ํธ)๋ forwardRef/memo๋ฅผ ์ฐ๋ฉด ์ด๋ฆ์ด ๊นจ์ง๋๋ฐ ์ค์ ํด์ฃผ๋ฉด DevTools์ Tab์ผ๋ก ํ์๋๋ค.
- ๋ฆฌ๋ ๋๋ง ๋ณผ ์ ์๋๋ก ์์
HOC (๊ณ ์ฐจ ํจ์ ์ปดํฌ๋ํธ)
- React์์ ์ฌ์ฌ์ฉ ๊ฐ๋ฅํ ๋ก์ง์ ์ถ์ํํ๋ ํจํด
- ์ปดํฌ๋ํธ๋ฅผ ์ธ์๋ก ๋ฐ์์ ์๋ก์ด ์ปดํฌ๋ํธ๋ฅผ ๋ฐํํ๋ ํจ์๋ฅผ ๋ปํจ
const withAuth = (WrappedComponent) => {
return (props) => {
if (!props.isLoggedIn) {
return <div>๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค</div>;
}
return <WrappedComponent {...props} />;
};
};
const Profile = (props) => <div>{props.user.name}์ ํ๋กํ</div>;
const ProtectedProfile = withAuth(Profile);
์์ฆ์ ์ปค์คํ ํ ์ผ๋ก ์ฌ์ฉ
// ์ธ์ฆ ์ฌ๋ถ๋ฅผ ์ ๊ณตํ๋ ํ
function useAuth() {
const [isLoggedIn, setIsLoggedIn] = React.useState(false);
const [user, setUser] = React.useState(null);
React.useEffect(() => {
// ์: ํ ํฐ ์ฒดํฌ, API ํธ์ถ ๋ฑ
const token = localStorage.getItem("token");
if (token) {
setIsLoggedIn(true);
setUser({ name: "์์ง" });
}
}, []);
return { isLoggedIn, user };
}
// ์ปดํฌ๋ํธ์์ ์ง์ ์ฌ์ฉ
function Profile() {
const { isLoggedIn, user } = useAuth();
if (!isLoggedIn) {
return <div>๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค</div>;
}
return <div>{user.name}์ ํ๋กํ</div>;
}
# forwordRef
- React ์์ ref๋ฅผ ์์ ์ปดํฌ๋ํธ๋ก ์ ๋ฌํ ์ ์๊ฒ ํด์ฃผ๋ ๊ณ ์ฐจ ์ปดํฌ๋ํธ (HOC)
- https://ko.react.dev/reference/react/forwardRef
- ํฅํ ์ฌ์ฉ ์ค๋จ ๋ ์์ ์ธ API ์ฌ์ฉ์ค
-> React 19 ์ด์๋ถํฐ๋ ํ์ํ์ง ์๋๋ฐ ์ฌ์ฉ์ค, ๋ฐ๊ฟ์ผํ ๋ฏ
React 19๋ถํฐ๋ ๋ ์ด์ forwardRef
์ด ํ์ํ์ง ์์ต๋๋ค. ์ด์ ref
๋ฅผ Prop์ผ๋ก ์ง์ ์ ๋ฌํ๋ฉด ๋ฉ๋๋ค.
forwardRef
๋ ํฅํ ๋ฆด๋ฆฌ์ค์์ ์ฌ์ฉ ์ค๋จDeprecated๋ ์์ ์
๋๋ค. ์์ธํ ๋ด์ฉ์ ์ฌ๊ธฐ์์ ํ์ธํ์ธ์.
Leave a comment