Course Content
Expert React
Expert React
4. Formik
6. Next Steps
Query String
Query parameter
A query parameter, also known as a query string, can include additional information or data in a URL. It is appended to the URL after a question mark (?
) and consists of key-value pairs separated by ampersands (&
). Query parameters commonly provide non-sensitive information and serve various purposes, such as search queries, data filtering, or configuration settings. For instance:
In this example, the query string is ?filter=fruits&sort=ascending
.
useSearchParams hook
React Router provides a hook called useSearchParams
to access and manipulate query parameters in the URL. By using this hook, we can work with query parameters effectively. Let's explore how to use it with an example to understand its functionality in practice.
Step 1: Import
Import the useSearchParams
hook from react-router-dom
:
Step 2: Initialize the hook
Access the query parameters using the useSearchParams
hook:
Step 3: Access query parameters
Work with query parameters.
Read a Query Parameter: Using the get
method of the searchParams
object, we can read the value of a specific query parameter. This is useful when you want to extract information from the URL and use it to control what content to display or how to configure certain components.
Update a Query Parameter: Sometimes, we need to modify a query parameter based on user interactions or changes in the application's state. Using the set
method of the searchParams
object, we can update the value of a specific query parameter and then apply the changes using setSearchParams
.
Delete a Query Parameter: We might want to remove a query parameter from the URL in specific scenarios. The delete
method of the searchParams
object allows us to do this. Removing a query parameter can be helpful when reverting certain filter settings or when specific actions reset the search state.
Everything was clear?