React, Flux, GraphQL, Hack, HHVM...? All of this and more!
Colocation of GraphQL queries is a growing trend in the world of React driven apps. What this means is that the data fetching GraphQL query is placed in the same location as the component's view logic. This is somewhat of a radical departure from the MVC architecture that many developers have been used to for decades.
One major project directly promoting the use of co-locating all the logic of a single component to the application is the Gatsby.js, which is a static site generator that uses GraphQL as an internal API. Example of a simple React component below:
import * as React from "react"; import Link from "gatsby-link"; export default ({ data }) => { const post = data.markdownRemark; return ( <div> <Link to="/">homepage</Link> <h1>{post.frontmatter.title}</h1> <div dangerouslySetInnerHTML={{ __html: post.html }} /> <i>{post.frontmatter.date}</i> </div> ); }; export const query = graphql` query BlogPostQuery($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title date } } } `;
This is only the latest move in how best practises evolve over time. A while ago placing template views, query logic and even display properties via CSS would have been an absolute abomination. Now, however it is considered best practice by many.
Tweet