Below is an introduction to the built-in hooks supplied by React, some ideas and rules for writing custom hooks, some useful hook libraries, and a real world authentication example.
Hook Definitions
The useState and useEffect hooks are the heavy lifters and will replace most of the functionality required by classes. Other built-in hooks provide some of the less frequently used React features that previously required classes.
useState
This hook is a replacement for state and setState. Calling useState creates a single state variable of any type with an optional initial value. Multiple and single calls can be used to contain an object called state.
import React, { useState } from 'react';
const WithState = (props) => {
/* Note: Unlike a class's setState, the merge for objects is not handled by setState. */
const [state, setState] = useState({foo: 'bar'});
const [input, setInput] = useState(''); ...}
useState returns an array whose first input will always be the current value of the state, and whose second value is a function used to update that value. The standard naming convention is name/set{name}.
useEffect
This hook allows side effects to be used in functional components. This is somewhat of a drop-in for class lifecycle functions such as componentDidMount and componentDidUpdate.
The function takes two arguments: a function with an effect to call, and an optional array with values on which to base the refreshing of that effect. The return is a cleanup function for the effect. A popular use case this could replace is subscribing to an event in componentDidMount and unsubscribing in componentWillUnmount.
import React, {useEffect, useState} from 'react';
import { AppState } from "react-native";
const WithSubscription = (props) => {
const [state, setState] = useState(AppState.currentState);
const handleStateChange = state => setState(state);
useEffect(() => {
AppState.addEventListener("change", handleStateChange);
/* This is called when the component unmounts or the effect is called again. */
return () => AppState.removeEventListener("change", handleStateChange);
});
...
}
The second argument is an optional but important array designating properties that, when updated, will cause the effect to be executed again. Ideally, all properties outside of the useEffect hook should be provided to this argument. This is equivalent to:
componentDidUpdate = (prevProps) => {
const {foo} = this.props
if(prevProps.foo !== foo) {
/* Effect */
}
}
useEffect(() => {
/* Effect */
}, [foo])
If the array is not provided, the effect will be run on every render. Conversely, if an empty array is passed, it is equivalent to componentDidMount and will only run once.
useContext
This hook provides the component with access to a context.
useMemo
This hook allows for the execution of expensive operations, keeping the value and only recomputing when specific properties change, like useEffect. This is useful when expensive non-primitive data is causing a useEffect to run on every render. Remember [] !== [] and {} !== {}!
useCallback
This hook is similar to useMemo, but will keep a function reference. Function instances are often redefined, so if this is causing rerenders, the hook can memorize the function. Again, remember () => {} !== () => {}.
Callbacks were created for both the navigate function and the dispatch wrapped login action using useCallback. This is to prevent rerenders as the function instances may change.
useReducer
Like a light form of Redux, this hook provides a dispatch function and a state, while taking a reducer and an initial state. Note that this is not a full replacement for Redux, though it could be used in certain situations.
useRef
As the name suggests, this hook allows components to use refs.
Check out the documentation for more information on these and other available hooks.
Custom Hooks
Among their many benefits, hooks can be customized to centralize and reuse logic. For example, consider the need to have a selected item in a list.
classListWithSelectionextendsComponent {
constructor(props){
super(props);
const {initialValue = ''} = props /* Initial value */
this.state = {selectedId: initialValue};
}
setSelectedId(id) {
this.setState({selectedId: id});
}
render() {
const { selectedId } = this.state;
return (
<scrollview></scrollview>
{
this.props.items.map(({id}) => (
onPress={() => this.setSelectedId(id)}
isSelected={selectedId === id}
/>
))
}
)
}
}
If this functionality appears in multiple parts of the app, it is likely that this state and logic is repeated. This is a great opportunity to implement a reusable hook.
const useSelectedId = (initialValue = '') => {
const [selectedId, setSelectedId] = useState(initialValue);
const isIdSelected = id => selectedId === id;
return {
selectedId,
setSelectedId,
isIdSelected,
}
}
Then, refactor the class into a functional component using the hook above.
const ListWithSelection = ({ initialValue, items }) =>
{ const {
selectedId,
setSelectedId,
isIdSelected,
items,
} = useSelectedId(initialValue);
return (
<scrollview></scrollview>
{
items.map(({ id }) => (
key={id}
onPress={() => setSelectedId(id)}
isSelected={isIdSelected(id)}
/>
))}
)
}
The component is no longer a class, the line count has gone down significantly, and the
this keyword is gone. The code has been written and is now reusable any time this logic is needed.
The Rules
The React team has provided a few rules to keep in mind when using hooks. Luckily, React has created an ESLint plugin to enforce these rules.
Only Call Hooks At the Top Level of Your Functional Component
This means no conditional calls to or looping with hooks. Not following this rule can lead to inconsistencies between renderings.
Bad
if(condition){
useEffect(...)
}
Good
useEffect(() => { if(condition){...}, [condition] })
Only Call Hooks from React Functions
This includes functions called from the render of a functional component. Calling a hook from a non-React function will trigger an error screen, and jest tests will fail.
Hook Libraries
react-redux
Instead of using the connect HOC, hooks can be used to get data and dispatch actions.
react-native-hooks
A collection of hooks to encapsulate parts of the React Native API.
react-navigation-hooks
Hooks for the react-navigation API. This library is fairly new and a great place to contribute and get involved.
react-spring
This library supports all react-based platforms and has hooks to handle complex animation logic.
react-apollo-hooks
In 3.0 Apollo will be adding hooks to react-apollo, but for now this library has a great set of hooks for your Apollo GraphQL needs.
A Real World Example
Let’s review a common use case: authentication. The user provides some input, an action is called to cause some reaction in the state, and the UI responds to any state change. Thanks to some of the hook libraries listed in the previous section, a class is no longer needed to implement this functionality.
import React, { useState, useEffect, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigation } from 'react-navigation-hooks';
import { login } from '../../actions/session';
const Auth = () => {
/* State */
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
/* Navigation */
const {navigate} = useNavigation();
/* Redux - mapStateToProps/mapDispatchToProps */
const dispatch = useDispatch();
const loginCallback = useCallback(
() => dispatch(login({email, password})),
[dispatch]
)
const {loaded} = useSelector(({session: {loginState}}) => ({
loaded: loginState.loaded,
}));
/* componentDidUpdate */
const navCallback = useCallback(() => navigate(routes.app));
useEffect(() => {
if(loaded){
navCallback();
}
}, [navCallback, loaded]);
style={style.container}
testID="authContainer"
>
value={email}
placeholder="Email"
onChangeText={setEmail}
/>
value={password}
label="Password"
secureTextEntry
onChangeText={setPassword}
/>
title="Log In"
onPress={() => loginCallback()}
>
}
After implementing all of the necessary hooks in the example above, the function looks a bit bulky and cluttered. Luckily, hooks are functions and can be refactored. Let’s create a custom hook and call it use AuthHooks to clean up the function.
import { useState, useEffect, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigation } from 'react-navigation-hooks';
import { login } from '../../actions/session';
const useAuthHooks = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigation = useNavigation();
const { navigate } = navigation;
const dispatch = useDispatch();
const loginCallback = useCallback(
() => dispatch(login({email, password})),
[dispatch]
)
const {loaded} = useSelector(({session: {loginState}}) => ({
loaded: loginState.loaded,
}));
const navCallback = useCallback(() => navigate(routes.app));
useEffect(() => {
if(loaded){
navCallback();
}
}, [navCallback, loaded]);
return {
state: {
email,
setEmail,
password,
setPassword
},
navigation,
dispatch,
loaded,
login: loginCallback,
}
}
This file now contains all the logic needed for the Auth component and the size of the component has been greatly decreased.
import React from 'react';
import useAuthHooks from './useAuthHooks';
const Auth = () => {
const {
email,
setEmail,
password,
setPassword,
loginCallback
}= useAuthHooks()
return (
style={style.container}
testID="authContainer"
>
value={email}
placeholder="Email"
onChangeText={setEmail}
/>
value={password}
label="Password"
secureTextEntry
onChangeText={setPassword}
/>
title="Log In"
onPress={() => loginCallback()}
/>
)
}
As you can see, hooks can greatly improve the readability and reusability of your React components, speeding up the development process and easing the chore of refactoring.
---
At FullStack Labs, we are consistently asked for ways to speed up time-to-market and improve project maintainability. We pride ourselves on our ability to push the capabilities of these cutting-edge libraries. Interested in learning more about speeding up development time on your next form project, or improving an existing codebase with forms? Contact us.