What Are Hooks?
Hooks are the functions that let you get to “state” without using a class component.
Rather than considering which lifecycle methods to use, you would now be able to write components thinking about how and when your data should be used.
React Hooks were introduced in October 2018 and released in February 2019. It is now available with React 16.8 and higher.
Why Are Hooks Popular?
- No boilerplate. You don’t need to import a new library or write any boilerplate code whatsoever, you can straightaway start using Hooks in React 16.8 and above.
- No need to use class components to use state. There is no more need to write class components even if we want to use state inside React components. Before, if we had written a functional component and we wanted to use state in it, we had to change it to a class component. With Hooks, we can use state inside functional components.
- Mounting and cleanup functions. You no longer have to think about when React mounts a component and what you should do in
componentDidMount
and remember to clean it up incomponentWillUnmount
. Hooks take care of all this stuff out of the box.
Enough about Hooks? Let’s move towards business…
Getting Started
npm install @apollo/react-hooks
This package exports the ApolloProvider
component to connect the client to your React app, just like the old API.
npm install graphql-tag
A JavaScript template literal tag that parses GraphQL query strings into the standard GraphQL AST.
Some Common Hooks
1. useState
useState
is used to set and update state like this.state
in a class component.
const [ state, setState] = useState(initialState);
2. useEffect
The Effect Hook lets you perform side-effects in function components. Side-effects could include things like DOM manipulation, subscriptions, and API calls.
useEffect(() => {
document.title = 'Hello World'
});
3. useReducer
An alternative to useState
. Accepts a reducer of type (state, action) => newState
, and returns the current state paired with a dispatch
method. (If you’re familiar with Redux, you already know how this works.)
const [ state, dispatch ] = useReducer(reducer, initialArg, init);
4. useContext
Accepts a context object (the value returned from React.createContext
) and returns the current context value for that context. The current context value is determined by the value
prop of the nearest <MyContext.Provider>
above the calling component in the tree.
When the nearest <MyContext.Provider>
above the component updates, this Hook will trigger a re-render with the latest context value
passed to that MyContext
provider.
Don’t forget that the argument to useContext
must be the context object itself:
- Correct:
useContext(MyContext)
- Incorrect:
useContext(MyContext.Consumer)
- Incorrect:
useContext(MyContext.Provider)
What Is GraphQL?
According to the official docs:
“GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.
GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.”
There are two main types of operations, queries and mutations.
Queries are used to retrieve data while mutations are used for creating/updating/deleting data.
Another important feature of GraphQL is that multiple operations can be performed using a single endpoint and a single network request. This reduces the number of roundtrips and overall data transfer, which is very important on mobile devices and bad network situations.
Examples
GraphQL mutation that adds a new user (and chooses which field to get a result on):
mutation CreateUser($name: String!){
createUser(name: $name) {
name
}
}
GraphQL query that gets the list of users:
{
users {
name
}
}
Real-world query example
First, we’ll create a GraphQL query named GET_DOGS
. Remember to wrap query strings in the gql
function to parse them into query documents:
Next, we’ll create a component named Dogs
. Inside it, we’ll pass our GET_DOGS
query to the useQuery
Hook:
As our query executes and the values of loading
, error
, and data
change, the Dogs
component can intelligently render different UI elements according to the query’s state:
- As long as
loading
istrue
(indicating the query is still in flight), the component presents aLoading...
notice. - When loading is
false
and there is noerror
, the query has completed. The component renders a dropdown menu that’s populated with the list of dog breeds returned by the server.
Real-world mutation example
Now that we know how to query for data, let’s look at how to create mutations.
Now we will see how to call the mutation we created above to save a record.
Conclusion
Hooks are a powerful addition to React. Also, React Hooks is a powerful library to use Hooks with GraphQL in your React app. I would recommend getting your hands dirty with Hooks now as you already have the foundation.
Did you learn something new today? Comments and feedback always make the writer happy!