Reputation: 14534
All I want is to run a piece of javascript code to query back-end GraphQL server. Why do I have to wrap my query in a HOC component? Like it says in this document.
import { Query } from "react-apollo";
import gql from "graphql-tag";
const ExchangeRates = () => (
<Query
query={gql`
{
rates(currency: "USD") {
currency
rate
}
}
`}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.rates.map(({ currency, rate }) => (
<div key={currency}>
<p>{`${currency}: ${rate}`}</p>
</div>
));
}}
</Query>
);
It looks like a very clumsy awkward solution? Why it has to be this way? Does it make things easier or more difficult? What is the philosophy behind it?
Update:
One thing trouble a lot is: I just want to make an API call, which is not visible, why do I have to render a tag inside render() function? API call are not supposed to be visible at all. This twist make me feel this whole HOC thing is a hack, bogus. What do you think?
Upvotes: 2
Views: 62
Reputation: 5432
They use Render Prop Pattern
because of it's highly declarative nature as outlined here
This encapsulation makes composing your Query components with your presentational components a breeze
Now about the Render Prop
itself, as per official react docs
The term “render prop” refers to a simple technique for sharing code between React components using a prop whose value is a function.
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
As described here this technique is React's favoured way of handling cross-cutting concerns.
Components are the primary unit of code reuse in React, but it’s not a always obvious how to share the state or behavior that one component encapsulates to other components that need that same state.
So with render prop
you put out only the public outcome of your encapsulated state that you want to share with other components.
render prop
is not HoC
, but is an alternative to it, that was recently embraced by the react team itself.
Upvotes: 1