
React: avoid setDefaultHook, use getParams
A colleague of mine helped identify a pattern that has turned out to be a bit of a footgun. The goal was: when a customer opens mysite.com/?urlParam=foo , I want to load the correct FooComponent. However, if mysite.com is opened with no param is set, I want it to default to FooComponent as well. In the following component, a hook is used to set some sort of default parameter: export const MyAdvancedComponent = () => { useSetDefaultParameters (); const { params } = usePlaygroundContext (); return ( < div className = "..." > { params . foo === " foo " && < FooComponent /> } { params . foo === " bar " && < BarComponent /> } .... The hook itself monitors the url params for changes and updates a context whenever urlParam changes. export const useSetDefaultParameters = () => { const urlParam = useGetUrlParam (); const { setParam } = useMyContext (); useEffect (() => { const defaultValue = defaults [ urlParam ]; setParam ( urlParam , defaultValue ); }, [ urlParam ]); };
Continue reading on Dev.to React
Opens in a new tab



