React: 기본값을 설정하는 hooks 피하기, 기본값이 있는 getter 사용
발행: (2026년 3월 13일 오후 07:49 GMT+9)
1 분 소요
원문: Dev.to
Source: Dev.to
문제
동료가 발사체가 될 수 있는 패턴을 식별하는 데 도움을 주었습니다.
사용자가 mysite.com/?urlParam=foo 로 열면 앱은 올바른 FooComponent 를 로드해야 합니다. 사이트를 쿼리 파라미터 없이 열 경우에도 기본적으로 FooComponent 로 로드되어야 합니다.
컴포넌트 예시
export const MyAdvancedComponent = () => {
useSetDefaultParameters();
const { params } = usePlaygroundContext();
return (
<>
{params.foo === "foo" && <FooComponent />}
{params.foo === "bar" && <BarComponent />}
{/* …other components */}
</>
);
};훅 구현
export const useSetDefaultParameters = () => {
const urlParam = useGetUrlParam();
const { setParam } = useMyContext();
useEffect(() => {
const defaultValue = defaults[urlParam];
setParam(urlParam, defaultValue);
}, [urlParam]);
};