- Here are some things you can do with Recompose:Optimize your React components by making them pure-renderedSet default propsAdd limited state variablesAnd you can do all of this while using the React functional component syntax, which makes your code much more straightforward and reduces your chances of accidentally introducing some state or complexity into your UI rendering.The React higher order component you use from react-apollo fits this mold.
- It just does one thing well: It enables you to co-locate your GraphQL query with your React component and get that data in your props, while handling all of the details like fetching and caching the data.
- That’s where React component composition and Recompose come in.We can attach GraphQL data, loading management, variable state, or pure rendering in just one function call!Without further ado, here is our first end-to-end example of how to use Recompose together with React Apollo to have a nice, concise UI with GraphQL!Manage your variables using ‘withState’The best feature of functional components is that they are stateless.
- However, sometimes you still want some temporary state, and it’s best to put that outside of the component that handles rendering to keep things clean.Let’s look how we can use the withState container from Recompose to build a React component that has both a search box and a GraphQL query that uses that search term:One nice side effect is that since we are keeping all of the state and data loading outside of the component, we can drop in the pure mix-in everywhere to make sure our components don’t rerender when they don’t need to.In the above code snippet, all of our concerns are very nicely separated through the React component paradigm.
- We could also use an HoC to flatten this out:Now, we can very easily share a common loading component between all of our UI that uses data from React-Apollo, and the logic is contained in a separate chunk that isn’t obscuring the structure of our pure component!Take-awayThe react-apollo API was designed to be the best way to pull GraphQL data into the props of a React component.
One of the main goals of Apollo Client and the Apollo project in general is to fit seamlessly into the modern React developer’s toolbox. That’s why we’ve invested in simple higher-order components…
Continue reading “Simplify your React components with Apollo and Recompose”