Managing query parameters in a React application can be challenging, especially when you need to synchronize them with your component's state.
Re...
For further actions, you may consider blocking this person and/or reporting abuse
What if the query parameter is mispelled or not found in the current URL? It would be great to have an optional fallback value as it may increase the size of the code to create a condition inside the useState just for this check.
Also, you could have saved some typings by using a useMemo instead of a useState + useEffect.
We could turn this code into the following.
Hello @aminnairi
Yes, you can make your custom hook more readable and efficient by using
useMemoinstead ofuseState+useEffectand by adding an optional fallback value for the query parameters. Here's how to apply these recommendations:Adding Optional Fallback Value:
By adding a second parameter to the
getQueryParamByKeymethod, you may offer an extra fallback value for query parameters. If the query parameter is misspelled or cannot be located, the fallback value will be sent back.Here's the updated
getQueryParamByKeyfunction:Now, you can provide a fallback value when calling
getQueryParamByKey:Using useMemo for Efficiency:
To use useMemo instead of
useState+useEffectfor initializingallQueryParams, you can do the following:By incorporating these changes, your custom hook will be more efficient and flexible.
Great, but I find the code a bit long. You can try RTK Query + useMemo.
Hello @skipperhoa
Thank you for your suggestion!
I agree that using RTK Query and useMemo can be a great optimization, especially for larger applications.
However, for beginners, I've opted for a simpler approach using useState and useEffect to manage query parameters. This approach is more beginner-friendly and easier to understand, making it a great starting point for those new to React development.
Feel free to modify the code as needed for your own projects!