React Hooks Fundamentals

Aradhya Singh
Catalysts Reachout
Published in
4 min readOct 8, 2022

This post is suited to React developers who are familiar with classes and new React developers who are wondering which one to use.

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

Why Hooks

Why are hooks being added to React, and how might they help you create fantastic applications?

We can transform all of our components into functional components by using hooks. This does not mean that class components no longer work, they can coexist alongside function components and hooks.

Benefit of using Hooks-

The advantages of hooks for developers are numerous, and they will improve the way we write components. They already assist us in producing code that is simpler and clearer.

Below is a side-by-side comparison that demonstrates how the component has shrunk a bit. With the switch to Hooks, we not only reduce the amount of code by around five lines, but also make it easier to comprehend and test the code. I would advise you to proceed cautiously because switching old code to Hooks could significantly reduce the amount of code and improve readability. Remember that Hooks may coexist with the code it’s replacing and is backward compatible with it, so there’s no immediate need to rewrite the entire codebase.

Before And After-

These are some Important Rules for Hooks

  1. Never call Hooks from inside a loop, condition or nested function
  2. Hooks should sit at the top-level of your component
  3. Only call Hooks from React functional components
  4. Never call a Hook from a regular function
  5. Hooks can call other Hooks

React provides a bunch of standard in-built hooks:

  • useState: To manage states. Returns a stateful value and an updater function to update it.
  • useEffect: To manage side-effects like API calls, subscriptions, timers, mutations, and more.
  • useContext: To return the current value for a context.
  • useReducer: This is similar to the useState Hook. A useState alternative to help with complex state management.
  • useCallback: It returns a memorized version of a callback to help a child component not re-render unnecessarily.
  • useMemo: It returns a memoized value that helps in performance optimizations.
  • useRef: It allows to directly create a reference to the DOM element in the functional component.
  • useLayoutEffect: This is very powerful hook and can help us to make important DOM measurements.
  • useDebugValue: The useDebugValue hook is simply used to print out debug information for custom hooks.

Let’s discuss some most needed React hook types.

useState( )

The information in this part will assist you in creating state values for your forms and updating them as necessary. How to change the name from “Brad” to “John” is as follows:

syntax- const [state, setState] = useState(initialState)

import React, { useState } from 'react'

function Component() {
const [name, setName] = useState('Brad')

if(name === "Brad"){
setName("John")
}

return <h1> My name is {name} </h1>
}//Returns: My name is John

Let’s look what’s going on in the code above.

You will need to import the useStatehook from the React package before you can use it.

It should be noted that the component makes use of ES6 array destructuring. The variable name within the array therefore relates to the argument of the function useState (current state). The variable setName(), on the other hand, refers to the function you will include to change the state. Consequently, this means that we have a state called name that we can edit by using the setName()function.

Since function components don’t have the setState() function, you need to use the setName() function to update it.

useEffect( )-

You can perform side effects in your components with the useEffect Hook. Timers, data fetching, and direct DOM updates are a few instances of side effects.

Syntax- useEffect(<function>, <dependency>)

import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);

useEffect(() => { document.title = `You clicked ${count} times`; });
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

Let’s explain the above code-

We first declare the count state variable before notifying React that an effect is required. The useEffect Hook receives a function from us. Our outcome is the function we pass. We use the browser API document.title to set the document title inside our effect. The most recent count can be read inside the effect because it falls under the purview of our function. React will keep track of the effect we used while rendering our component and then execute our effect after updating the DOM. Every render, even the initial one, experiences this.

The function that is supplied to useEffect on each render will be different, as seasoned JavaScript developers may have noticed. It’s done on purpose. Actually, it is because of this that we are able to read the count value from within the effect without being concerned that it would become stale. We schedule a new effect to take the place of the old one each time we render. Each effect “belongs” to a certain render, which in a way makes the effects behave more like a component of the render output.

--

--