DEV Community

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

Posted on

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.

Top comments (0)