React: avoid hooks that set default values, use getters with defaults
Source: Dev.to
Problem
A colleague helped identify a pattern that can be a foot‑gun.
When a user opens mysite.com/?urlParam=foo, the app should load the correct FooComponent. If the site is opened without any query parameter, it should default to FooComponent as well.
Component Example
export const MyAdvancedComponent = () => {
useSetDefaultParameters();
const { params } = usePlaygroundContext();
return (
<>
{params.foo === "foo" && <FooComponent />}
{params.foo === "bar" && <BarComponent />}
{/* …other components */}
</>
);
};Hook Implementation
export const useSetDefaultParameters = () => {
const urlParam = useGetUrlParam();
const { setParam } = useMyContext();
useEffect(() => {
const defaultValue = defaults[urlParam];
setParam(urlParam, defaultValue);
}, [urlParam]);
};