A Quick Introduction to React Hooks

react unimedia
React Hooks are inbuilt React functions that allow developers to manage state and perform logical actions in a React function component.

Table of Contents

In this article, we will briefly learn what React Hooks are, the types of hooks, and also basic examples of using some of these hooks in your React app.

You may also be interested in: “Stripe Checkout Integration with React”

What Are React Hooks?

React Hooks are built-in functions that allow you to use state within function components. Introduced as special APIs in the React 16.8 version released in 2019, Hooks will allow you to ‘hook into’ React features such as lifecycle methods. A feat that was previously only possible using class components. 

React Hooks are incredibly powerful because they allow React developers to transform stateless functional components from just rendering reusable UIs to being capable of saving and maintaining state and logic. Before that, developers found it hard to reuse logic and share state between class components without using even more complex react abstractions. React Hooks made it possible to extract both stateful logic between components. 

In summary, here are benefits that developers gained from the introduction of React Hooks. 

  • More straightforward code structure that does away with the ‘this and binds’ keywords.
  • Easier to reuse logic and share state without dealing with complex React abstractions that are hard to test and manage.
  • A more precise top-down one-way data flow is possible without disrupting your existing components’ order. 
  • When optimally used, React Hooks can help you do away with the need to integrate a state management library.

Common React Hooks

There are various types of in-built react hooks. You can even create your own Custom Hooks containing your own desired functional logic, which you can reuse across different components. 

The React 16.8 release came with ten built-in hooks categorized into two:  Basic Hooks and Additional Hooks. Of these hooks, we will examine two hooks that are the most commonly used: useState and useEffect.  

UseState React Hook

The useState Hook is the most popular React hook. It allows you to ‘use state’ in a function component. This means you can read, manipulate and update state using the useState Hook. 

A basic rendition of the useState Hook is shown below:

const [state, setState] = useState(initialState);

For example, the sample above has a state which is initially the same value as initialState. The initialState can take a number, string, or even an array depending on the data type at hand. setState is a function that’s used to update the state value. E.g. setState(updatedState).  

Let’s use the useState Hook in a simple, functional component. 

function Age() {
 const [age, setAge] = useState(10);
 
 return (
     <div>
         <p>I am {age} Years Old</p>
       <div>
          <button onClick={() => setAge(age + 1)}>Increase my age!      </button>
          <button onClick={() => setAge(age - 1)}>Decrease my age! </button>
       </div>
     </div>
 )
}

Let’s quickly explain how the above code works:

  • We have the basic rendition of the hook:
    const [age, setAge] = useState(10);

age has an initial state of 10 which we then call between the <p> tag.

  • The buttons have an onClick handler which calls the setAge function, which will increase and or decrease our initial age state depending on the button clicked. 

UseEffect React Hook

The useEffect Hook accepts a function that it runs after each render. It’s commonly used for performing side effects. This can range from manipulating the DOM or Browser APIs or even fetching data from external APIs. The useEffect hook also helps us achieve capabilities in a function component previously done by React lifecycle methods. Think of the useEffect Hook as the combination of the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods. Besides, we can also set the useEffect hook to render based on specific value changes.

Here’s a basic rendition of the useEffect Hook.

useEffect(functionToRun);

For example, let’s use the useEffect Hook more elaboratively using the previous functional component sample.

function Age() {
 const [age, setAge] = useState(10);
 
 useEffect(() => {
   setAge(20)
 },[]);
 
 return (
   <div>
     <p>I am {age} Years Old</p>
     <div>
       <button onClick={() => setAge(age + 1)}>
         Increase my age!
       </button>
       <button onClick={() => setAge(age - 1)}>
         Decrease my age!
       </button>
     </div>
   </div>
 );
}

The useEffect at render sets the new age value to 20. We also passed an empty array which will let the useEffect hook run once only.

I’ve placed a console.log in the display above. We can see how the value of age state changed from the initial 10 to 20, caused by the useEffect hook. We then see how the state changes as we click the button.  

Other React Hooks

There are also other Hooks such as useContext(), useMemo(), amongst others. You can have a look at the rest in the official documentation.

There are, however, two rules you should follow when using React Hooks. 

  • Always call hooks at the top level, as shown in the examples we’ve used. This means that we can’t call hooks inside loops, conditions, or nested functions.
  • Only use Hooks from inside React function components.

Many Code IDEs like VSCode have an inbuilt linter that enforces these rules and more.

Users App

Finally, let’s create a more complex app using all we’ve learned about React, useState, and useEffect Hooks. 

We will be fetching data from an external API with fake users data. As we’ve learned, this is a perfect use case for the useEffect Hook.

function Users(){
 const [users, setUsers] = useState([]);
 useEffect(() => {
       fetch("https://jsonplaceholder.typicode.com/users/")
           .then(res => res.json())
           .then(data => setUsers(data))
     }, [])
 
 return (
     <ul>
         {users.map(user => (
         <li key={user.id}>
             {user.name}lives in {user.address.city}
         </li>
         ))}
     </ul>
 );
}

In the sample above, you can see how we’ve used:

  • The useState hook to set and update state including inside the useEffect Hook.
  • The useEffect hook interacts with the Browser API called Fetch, which allows us to cull data from external APIs. We also passed an empty array to make sure it ran once.

Again in the video above, I’ve placed a console.log so you can see how we pulled out specific data to display. 

Summary

We had fun! React Hooks are really powerful when used correctly. In conclusion, we learned what React Hooks are and the immense benefits they bring to developers. In addition, we also briefly examined the various types of hooks and the rules guiding their usage. Lastly, we created a simple React app that demonstrated how to use the useState and useEffect hooks.

If you’re feeling adventurous and want to build more apps with React hooks, check out our Stripe Checkout Integration with React article.

Unimedia Technology

Here at Unimedia Technology we have a team of React Developers that can help you develop your most complex react Applications.

Remember that at Unimedia, we are experts in emerging technologies, so feel free to contact us if you need advice or services. We’ll be happy to assist you.

Unimedia Technology

Your software development partner

We are a cutting-edge technology consultancy specialising in custom software architecture and development.

Our Services

Sign up for our updates

Stay updated, stay informed, and let’s shape the future of tech together!

Related Reads

Dive Deeper with These Articles

Explore more of Unimedia’s expert insights and in-depth analyses in the realm of software development and technology.

Let’s make your vision a reality!

Simply fill out this form to begin your journey towards innovation and efficiency.