When learning about react, how useful is it to know about react hooks and components?

Rasitharoshana
11 min readMay 15, 2022

React is a JavaScript library used to create user interfaces. Let’s begin by discussing the two distinct sections of this term.

React is a “library” for JavaScript. It’s not quite a “framework.” It’s not a comprehensive solution, and you’ll almost always need to combine it with other libraries to make a complete solution.

React makes no assumptions about the other components of a solution.

Frameworks are particularly useful for young teams and startups. Many smart design decisions are already made for you when working with a framework, allowing you to focus on implementing strong application-level logic.

Frameworks, on the other hand, have certain drawbacks. These drawbacks might be a deal breaker for experienced engineers working on huge codebases.

Although some profess to be, frameworks are not adaptable. A framework normally expects you to code in a specific style.

If you try to veer from that path, the framework will almost always resist you. Frameworks are often vast and feature-rich.

Even if you just require a tiny portion of them, you must provide the entire set.

Although this situation is improving, it is still not ideal.

Some frameworks are moving toward modularity, which I think is fantastic, but I am a firm believer in the pure Unix philosophy:

Why is React called “React” in the first place?

The UI it portrays (its output) changes when the state of a React component (which is part of its input) changes. The device we’re dealing with needs to reflect this change in the UI description. The DOM tree must be updated in a browser. We don’t do that manually in a React application. Respond will simply react to state changes and update the DOM automatically (and effectively) as needed.

Components are key in React.

We discuss UIs using reusable, composable, and stateful components in React.

We specify minor components before combining them to make larger ones. All components, no matter how tiny or large, are reusable between projects.

Components can be thought of as simple functions (in any programming language).
With some input, we call functions, and they return some output. We can reuse functions as appropriate and combine them into larger functions.

React components have the same input and output: a set of “props” and a description of a user interface. A single component can be reused across numerous UIs, and components can contain additional components. A React component is essentially a JavaScript function in its most basic form.

Although certain React components are pure, you can also add side effects to them. When a component is mounted in the browser, it might change the HTML “title” of a web page or scroll the browser view to a specific place.

Most crucially, a React component can contain a private state to store data that changes across the component’s lifecycle.

This private state is an implicit aspect of the input that drives the output of the component, and it’s what gives React its name!

Component advantages

Many additional frameworks and libraries use the term “component.” We can even use HTML5 technologies like custom elements and HTML imports to develop native web components.

Components have numerous advantages, whether we use them directly or through a library like React.

To begin with, components make your code more readable and manageable. Consider this user interface:

When things get more complicated, parsing HTML gets more difficult, thus components help us rapidly understand what a UI represents in a language we’re familiar with.

We know exactly what this UI symbolizes without even looking at the HTML code. Furthermore, we know exactly where to go if we need to change the output of the remaining characters section.

React components can be reused both within and between projects. Here’s an example of how the ClickableImage component could be implemented:

This component is reusable because it has variables for both the href and src props. To use this component, for example, we can render it with the following props:

Functions vs classes

In React, components generated with functions were previously restricted. The class syntax was the sole way to make a component “stateful.” Beginning with React version 16.8, which was released in early 2019, this has changed with the release of “React Hooks.” A new API for making a function component stateful was introduced with the React hooks release (and give it many other features).

The majority of what is normally done with React can now be done using functions thanks to this new API. Only advanced and extremely rare cases require class-based syntax.

I believe that the new API will gradually replace the old one, but that isn’t the only reason I want you to utilize it (exclusively if you can).

I’ve used both APIs in huge apps and can tell you that the new one is considerably superior to the old one for a variety of reasons, but here are some of the most important to me.

You don’t have to deal with “instances” of classes or their implicit states. You deal with basic functions that are updated with each render.

Nothing is hidden and the state is plainly declared. All of this basically means that your code will have fewer surprises.
Related stateful logic can be grouped and separated into self-contained composable and sharable components.

This makes breaking down complex components into smaller pieces much easier. It also facilitates component testing.
Any stateful logic can be consumed declaratively, without the necessity for hierarchical “nesting” in component trees.

While class-based components will remain in React for the foreseeable future, as a novice to the ecosystem, I believe it is best to begin with simply functions (and hooks) and concentrate on understanding the new API (unless you have to work with a codebase that already uses classes).

Creating components using classes

React also allows you to create components using the JavaScript class syntax. Here’s an example of the same Button component written in class syntax:

You define a class that extends React.Component, one of the core classes in the React top-level API, with this syntax.

At the very least, a class-based React component must define a render instance method.

The element that represents the output of an object constructed from the component is returned by this render method.

When we utilize the Button class-based component (by rendering a Button… />), React will generate an object from it and use the representation of that object to create a DOM element.

It’ll also link the DOM-rendered element to the instance of the class it produced.

Constructor of Components

If your component has a constructor() function, it will be called when the component is first started.

The constructor function is where the component’s properties are started.
Component properties should be kept in a state object in React.

Later in this tutorial, you’ll discover more about state.
In the constructor function, you can also honor the parent component’s inheritance by including the super() statement, which performs the parent component’s constructor code, giving your component access to all of the parent component’s functions (React.Component).

Creating components using functions

Functional components are the first and most preferred component type in React. A functional component is a React element that is returned by a JavaScript/ES6 function (JSX). The following function is a valid functional component, according to React’s official documentation:

In React, a functional component is:

A React element must be returned via a JavaScript/ES6 function (JSX)
Always starts with a capital letter (name convention) and, if necessary, takes props as a parameter

What are hooks, exactly?

A hook is a call to a particular function in a React component. The word “use” starts every hook function.

Some of them, like useState, can be used to provide a function component with stateful elements, while others, like useEffect,

can be used to handle side effects or cache/memorize functions and objects (like useCallback).

Hooks are extremely powerful, and the possibilities are endless when it comes to what you can accomplish with them.

Only function components can use React hook functions. They aren’t allowed in class components.

Make the Button component above respond to a click event to see an example of the simple useState hook.

Let’s keep track of how many times it’s been clicked in a “count” variable and use that value as the label for the button it renders.

We’ll use this count variable to introduce the state element to the example. Because we’re displaying it, it’s a piece of data that the UI will rely on, and it’s a state element because it will change over time.

You introduce a state every time you define a variable in your code, and you mutate that state every time you modify the value of that variable. Take that into consideration.

We must first learn about occurrences before we can change the value of the count state.

State Hook

useState is a Hook in this case (we’ll explain what that means later). To add some local state to it, we call it inside a function component.

Between re-renders, React will keep this state. useState returns a pair of values: the current state and a function to update it.

This function can be called from an event handler or from anywhere else. This is comparable.

Except that setState in a class does not combine the old and new states. (We’ll compare useState to this with an example.) (See Using the State Hook for more information.)

Effect Hook

You’ve probably used React components to execute data fetching, subscriptions, or manual DOM changes previously. These actions are referred to as “side effects” (or “effects” for short) since they have the potential to affect other components and cannot be performed during rendering.

The useEffect Effect Hook gives a function component the ability to perform side effects. It accomplishes the same thing as React’s componentDidMount, componentDidUpdate, and componentWillUnmount methods, but in a single API. (In Using the Effect Hook, we’ll compare useEffect to these methods with examples.)

For example, after React changes the DOM, this component sets the document title:

You tell React to run your “effect” code after flushing changes to the DOM when you call useEffect. Effects are specified within the component, giving them access to its props and state.

React runs the effects after every render by default, including the first one. (In Using the Effect Hook, we’ll go through how this relates to class lifecycles.)

By returning a function, effects can optionally define how to “clean up” after themselves. This component, for example, utilizes an effect to subscribe to a friend’s online status and then unsubscribes:

Additional Hooks

There are a couple of lesser-known built-in Hooks that you could find handy.

UseContext

UseContext, for example, allows you to subscribe to React context without having to utilize layering.

useReducer

And useReducer lets you manage local state of complex components with a reducer:

useCallback Hook

The React useCallback Hook returns a callback function that has been memorized.
Consider memoization to be the act of storing a value so that it does not have to be recalculated.

This allows us to separate resource-intensive routines from the rest of the render so that they don’t run every time.
The use
The Callback Hook is only activated when one of its dependencies changes.
This can help you perform better.

UseCallback and useMemo are comparable hooks. UseMemo returns a memoized value, whereas useCallback returns a memoized function.

Building Your Own Hooks

We occasionally wish to reuse stateful functionality across components. Higher-order components and render props were traditionally two prominent solutions to this challenge.

You can do this using Custom Hooks without adding new components to your tree.

We established a FriendStatus component earlier on this page that uses the useState and useEffect Hooks to subscribe to a friend’s online status.

Assume we wish to reuse the subscription functionality in another component.

We’ll start by putting this logic into a new Hook named useFriendStatus.

It accepts the parameter friendID and returns whether or not our friend is online.

We can now use it in both components:

Each component’s state is totally autonomous. Hooks, not state, are a mechanism to reuse stateful logic.

In fact, each call to a Hook has its own state, so you can use the same custom Hook in two different components.

Custom Hooks are a convention rather than a feature. We call a function a custom Hook if its name starts with “use” and it calls other Hooks.

Our linter plugin uses the useSomething naming convention to discover flaws in the code using Hooks.

You can create custom Hooks for a variety of scenarios, including form handling, animation, declarative subscriptions, timers, and probably a lot more that we haven’t thought of yet.

We’re looking forward to seeing what custom Hooks the React community creates.

Rules of Hooks

Hooks are JavaScript functions with two additional constraints:

Hooks are only called at the highest level. Hooks should not be called from within loops, conditions, or nested functions.

Hooks can only be called from React function components. Hooks should not be called from ordinary JavaScript functions. (You can only call Hooks in one other place: your own custom Hooks.) We’ll learn more about them later.)

We provide a linter plugin that automatically enforces these requirements.

We recognize that these criteria may appear restrictive or perplexing at first, but they are necessary for Hooks to function properly.

--

--