We're planting a tree for every job application! Click here to learn more

React: Understand what a hook is

Adrian Garcia Estaun

8 Dec 2022

3 min read

React: Understand what a hook is
  • TypeScript

These last months I have seen that many people from my team were a bit confused about how the hooks work in our React Native application. In this post I’m going to answer some basic questions about them and I will show some examples to make it clearer.

What’s a hook?

A hook is a simple function that allows you to access the React Framework. That means that we get access to another hooks, for example useState, useEffect, useLayoutEffect, useMemo, useCallback, useImperativeHandle, etc… You might want to check all the hooks that React provide us. Check them out here.

Do I need to use hooks?

No. But I really encourage you to try them if you haven’t done it yet. They will open up a range of possibilities, improving your React or React Native application, avoiding duplications, and making your code cleaner, more readable and organized.

Do I need to know anything before using them?

The most important things that you need to be clear about are these:

  • Hooks are only available for functional components, not for classes. If you are not familiar with functional components, read about them first here.
  • Hooks must use the use prefix keyword. For example, useLoggedUser, useConnection, useBluetoothListener, etc. Just remember to add the use prefix when declaring a hook function.
  • Hooks are backwards-compatible. You can start using them in your new components and be sure that everything will continue working as before. At some point you might want to migrate those class components to functional components where you consider to use hooks. You can create your own hooks defining a piece of logic and reusing it throughout your app.

Blah blah blah… Where is the code?

I know, I know… we are developers and we need examples to see if we are really interested on implementig this. Let’s see a basic example.

import { useEffect, useState } from 'react';
import { Text } from 'react-native';

// Functional component.
const BasicTimer = () => {
 
  const [seconds, setSeconds] = useState(0); // First hook.
  
  // Second hook.
  useEffect(() => {
    setTimeout(addSecond, 1000);
  });

  const addSecond = () => {
    setSeconds(seconds + 1);
  };

  return <Text>{`Seconds elapsed ${seconds}`}</Text>;
};
export default BasicTimer;

Here you can see a small functional component that prints the seconds elapsed since the component was mounted the first time.

The first hook is the useState hook, and it help us to keep the seconds elapsed in memory during the lifecycle of the component. This is the way it works:

  • To use it you have to declare the hook with useState(initial value). In this case we are using typescript and it has type inference. This means that we don’t need to define the type if we don’t want, because the compiler infers the type automatically when a value is assigned. In this case we set 0 as inital value, so the type is number.
  • The hook returns 2 values. The first one is the variable that contains the value (in this case 0). The second is a function to allow us to update the value whenever we need. For example, when we call setSeconds(seconds + 1);

Remember, useState is asynchronous. That means that if you check the value (seconds) just one line below the line that updates the value (setSeconds) the value will be the same as you had before calling the setSeconds function.

// Replace addSecond by this function to see that useState is asynchronous.
const addSecond = () => {
  console.log('Seconds elapsed before calling setSeconds:', seconds);
  setSeconds(seconds + 1);
  console.log('Seconds elapsed after calling setSeconds:', seconds);
}

Let’s move forward with the useEffect hook. This hook helps us to call a function every time that React renders the component. This is the way it works:

  • To use it you have to declare the hook with useEffect(callback, dependencies array).
  • The first parameter is a function/callback that you want to call after the component is rendered.
// You can pass the function you want to call.
useEffect(myCallback);

const myCallback = () => {
   setTimeout(addSecond, 1000);
}
  • The second is an array of values/dependencies to allow you to control when to call the function. It can be called once, everytime a value/dependency changes, or everytime React re-renders the component. This means that it will be executed at least once (when the component is rendered the first time), but it may or may not be called every time the component is re-rendered.

But you don’t pass any second parameter

The second parameter is optional, and it works this way:

  • If it’s an empty array the function will be called only after the component has been mounted. It does not matter if the component is re-rendered. Only once.
useEffect(() => console.log('Hello World!'), []);
  • If the array is not passed at all, the function will be called every time the component is rendered. That’s it, always.
useEffect(() => console.log('Hello World!', Date.now()));
  • If the array contains values, React will check if any of those values has changed since the function was called the first time. It’s a conditional call.
const [time, setTime] = useState(Date.now());
useEffect(() => console.log('Hello World!', time), [time]);

Try to update the time variable calling setTime(Date.now()) inside the useEffect. You will create an infinite loop.

Summary

  • Hooks are functions with access to React’s features.
  • You can create your own hooks.
  • They can receive params and return values.
  • They can use another hooks into them.
  • Only accessible from functional components.
  • Their use is optional.
  • To learn more about hooks check the official documentation.

Hope you enjoyed the post.

Made with ❤️ for those who want to learn and teach.

Did you like this article?

Adrian Garcia Estaun

Whenever I encounter a new challenge, I make sure to learn about it so I can deliver the best results. Keeping up with the latest in technology is not just important for my professional growth, but also because I'm genuinely interested in it.

See other articles by Adrian

Related jobs

See all

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Related articles

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

WorksHub

CareersCompaniesSitemapFunctional WorksBlockchain WorksJavaScript WorksAI WorksGolang WorksJava WorksPython WorksRemote Works
hello@works-hub.com

Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ

108 E 16th Street, New York, NY 10003

Subscribe to our newsletter

Join over 111,000 others and get access to exclusive content, job opportunities and more!

© 2024 WorksHub

Privacy PolicyDeveloped by WorksHub