DEV Community

Cover image for React Query Custom Hooks Example in react js
Rajiv Chaulagain
Rajiv Chaulagain

Posted on

5

React Query Custom Hooks Example in react js

Let's create a custom hook with react query.
Now we will create a component that fetches list of products with react query.

Now in Product.js component ,

const Product = () => {
  const products = useProducts()
   if(products.isLoading) return "Loading ....."
   if(products.isError) return "Error ...." 
  return(
   <>
      products.map((product) => (
     <h4 key={product.id}>{product.title}</h4>
  ))
   </>
)
}
Enter fullscreen mode Exit fullscreen mode

Lets create a hook as useProducts.js

const useProducts = () => {
  return useQuery(['products'] , getProducts)
};

Enter fullscreen mode Exit fullscreen mode

Now if we want to fetch single data then we can pass id

const Product = () => {
const params = useParams();
const id = Number(params?.id)
  const product = useProduct(id)
   if(product.isLoading) return "Loading ....."
   if(product.isError) return "Error ...." 
  return(
   <>
     <h4>{product.title}</h4>
  ))
   </>
)
}

const useProduct = (id) => {
  return useQuery(['product' , id] , () => getProduct(id))
};
Enter fullscreen mode Exit fullscreen mode

Now for post and edit,

const AddProduct = () => {
  const mutation = useAddProduct()
  const [data , setData] = useState('');
  return(
   <>
    <input value={data} onChange={(e) => 
        setData(e.target.value) } /> 
    <button onClick={mutation.mutate(data)}></button>
   </>
  )
)
};

const useAddProduct = () => {
  return useMutation(postProduct , {
  onSuccess : () => {
    toast.success(`Added successfully`)
  }
})
};

Enter fullscreen mode Exit fullscreen mode

for edit ,

const EditProduct = () => {
  const params = useParams();
  const id = Number(params.id);
  const mutation = useEditProduct()
  const [data , setData] = useState('');
  return(
   <>
    <input value={data} onChange={(e) => 
        setData(e.target.value) } /> 
    <button onClick={mutation.mutate(data , id)}></button>
   </>
  )
)
};

const useEditProduct = () => {
  return useMutation(editProduct , {
  onSuccess : () => {
    toast.success(`edited successfully`)
  }
})
};
Enter fullscreen mode Exit fullscreen mode

Conclusion,

This is the best way to manage the server side data and separate the business logics with the UI components and hence anyone from outer world can check , edit and understand the code. This is the best way to work with react and only the needed component will use the data from the custom hook.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more