Using React Native Hooks — notes

NR
Personal Project

--

React Native Hooks. One of the latest additions to the React (Native) framework. Hooks were officially released in React 16.8 and React Native since the 0.59 version.

What are Hooks?

Hooks are the solution to let you use state and other React features in a function component. Before the 16.8 version, class components were privileged with managing the state, extending PureComponents and having lifecycles.

Functional Components could never do these choirs since it wasn’t supported. If you were writing a function component and suddenly realize that your component should hold a state you just had to change the whole thing to a class component. Here’s where Hooks come in: Hooks make it possible to add a state to a functional component or let it hook into a lifecycle method.

To put it simply: Hooks mean the end of stateless function components, as they give these the option to manage state and lifecycle features by themselves now. You would use it if a function component requires a state instead of rewriting the component to a class.

Built-in Hooks

To make it easier for us, React provides the most used practices of state management as built-in hooks. I will introduce the 2 most well-used. These are also the ones I used the most in my project. If you want to re-use the state between different components you can also opt to code your own Hooks.

useState Hook

useState is the function component equivalent for setState. You can use it inside a function component to use and modify the local state. It’s imported at the top as:

import React, { useState } from 'react';

useState returns a pair: the current state value and a function which can update the state value:

const [count, setCount] = useState(0);

Here count is the state, setCount is the function. setCount can be compared to this.setState but with one exception: setCount won’t merge the old state and new state instead, it creates a completely new state which replaces the old state.

You can choose whatever name you want for the state value and update function. It’s also possible to have multiple useState hooks in one component:

const [name, setName] = useState("Lisa");
const [age, setAge] = useState('23');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);

As shown in the example, it is possible to pass an argument to the useState. For example, we pass the argument Lisa, 23 and Learn Hooks to the previous useState Hooks. You can also pass a boolean value to it or when a state needs x values, you call useState x times.

You can read and update the state as following in React Native:

<Text>You clicked {count} times</Text>
<Button title="Click me" onClick={() => setCount(count + 1)} />

useEffect Hook

The useEffect Hook lets you execute side effects from a function component. These side effects can be fetching some data, subscriptions or manually changing the DOM from components. They’re called (side) effects because they can affect other components and can’t be executed during rendering.

This Hook unifies the lifecycle methods from class components such as componentDidMount, componentDidUpdate, and componentWillUnmount.

By default, the useEffect Hook runs after every render including the first one and it is also possible, just like useState, to make use of multiple effect hooks in one component. This is recommended to separate concerns.

useEffect is imported next to useState:

import React, { useState, useEffect } from 'react';

The syntax of useEffect:

useEffect(() => {
document.title = `You clicked ${count} times`;
});

The useEffect Hook will now update manually update the DOM document title with the state.

#TIP: if you want to make sure that the useEffect Hook only re-renders when needed, i.e. when the count is updated, you’ll need to add a second argument to the syntax. This argument will be an array that will be used by every re-render to compare if it has changed. For example:

useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);

Let’s assume count is 6, for the next re-render React will compare the newest count to its previous state. If it still has the same value, React will skip the useEffect. If the count value has changed, it will re-run the useEffect Hook.

It’s also possible to just give an empty array as second argument. This means that the useEffect Hook will only be executed once and will break the infinite loop.

One more hook I want to tell you about is:

useCallback Hook

useCallback is a Hook that I very often used in my project. This Hook helps you executing a function only when one if it’s dependencies changed. It can be compared to shouldComponentUpdate.

Import the Hook next to useState:

import React, { useState, useCallback } from 'react';

And use it as follows:

const toggleFavoriteHandler = useCallback(() => {
dispatch(toggleFavorite(spotId));
}, [dispatch, spotId]);

You pass in a function and 2 dependencies. The function here is the dispatch function which holds another function. The dependencies are dispatch and spotId. These dependencies are very imported since they are the reference for whether or not the useCallback Hook should execute the (dispatch) function.

Whenever one of the dependencies changes, the useCallback will allow executing the function. Another example to make it clearer:

const decrease = useCallback(() => {
setCount(count - 1)
}, [setCount, count])

The setCount function will be executed when setCount or count changes. It’s important to note that the dependencies should be part of the function.

Rules of Hooks

There are two super important rules for using Hooks:

Only call Hooks at top level

You can’t use Hooks inside conditions, loops or nested functions. React will definitely throw you an error when you try to do this. The reason for this rule is if Hooks are called top-level, they will always be executed with every (re-)render.

If you conditionally want to run an effect, you can put that condition inside the useEffect Hook.

Only call Hooks from React (Native) Functions

You can only make use of Hooks when you use them in React function components or in custom build Hooks.

ESLint Plugin

React supplies an easy tool to make sure you use Hooks correctly: an EsLint Plugin. Add it to your project by:

npm install eslint-plugin-react-hooks --save-dev
#OR
yarn add eslint-plugin-react-hooks --save-dev

Opinion

Advantages

  • Better readable syntax: I find it easier to add, use and change state management throughout my components. The lesser the code lines, the better!
  • More consistency: Thanks to Hooks, there is now the possibility to only use functional components through your whole project. This makes it easier to understand and learn.

Disadvantages

  • Abstract: coming from a class component use of state management, it can be very overwhelming to use Hooks. It’s a must to read into the documentation and further research otherwise it looks very complex. I also advise you to try and train as much as you can.
  • Under documented: if you’re used to working with class components and states and you suddenly want to try out Hooks for a new app, I wish you good luck. When the Hooks information itself is well documented, some other React features with the implementation of Hooks are not. When you’re searching for some more information or an answer to one of your React problems, very often the given information still uses the old state management system. This sometimes makes it easier to understand and imply the code. But I’m sure that this will evolute over the next few years.

Note: make sure you have the newest version of react and react-dom. Otherwise, it will give you a bunch of errors from the server-side not recognizing hooks. Make sure you updated these!

P.S If you’re a really big fan of Class components and fear their exit. Don’t be, React strongly implies that there are no plans to remove classes from React. Hooks are more of a gradual addition but not a complete replacement. React also strongly advises to not rewrite already existing components to use Hooks.

#TIP: https://usehooks.com/ is the perfect website to find new Hooks with understandable and simple examples that will definitely help you to use them in your next project!

So here we are, at the end of this article and of my notes on learning the (basic) of Hooks in React. During my project, I really tried to make use of the newest techniques and implementations. Thanks to this, using Hooks is an unavoidable practice.

Make sure to follow me for more problems and solutions I come across within React Native and Machine Learning!

--

--

NR
Personal Project

Trying to figure things out while writing about it. Pixel-perfect friend, front-end developer and anything data-related geek