Home  >  Blog  >   React JS

React Hooks Tutorial

Rating: 4.6
  
 
3005

Reactjs is an explanatory and effective javascript library to build recyclable UIComponents. It is accountable for the view level of the application. Hooks is the latest feature added in the React 16.8 edition. Hooks uses the react features without implementing the class.

In this React Hooks Tutorial, we will learn all the essential concepts of React Hooks

Hook Tutorial - Table of Content 

What is Hook?

Hooks are a new inclusion in React 16.8. Hooks allow us to utilize the react features without the help of the class. Hooks give API to the React Principles like state, props, refs, etc. Hooks can also blend the principles of reacting.

Need for Hooks

When you need to develop a function component, and after that, if you need to include any state to it, earlier we do that by transforming it into a class. However, now we can do that by utilizing the Hook in the present function component.

Rules of Hooks

Hooks are identical to the functions of Javascript, yet we are required to obey the following rules while using hooks. The regulations of hooks assure that complete stateful logic inside the component is apparent in the source code. The rules are:

  • Invoking Hooks at Higher Level
    • We should not invoke Hooks from Conditions, Nested Functions, Loops. We can invoke hooks from the high level of our react functions. By this rule, we can invoke the hooks in a similar order every time a component produces.
  • Invoking Hooks through React Functions
    • Through standard javascript methods or functions, we cannot invoke hooks. Instead, we can invoke hooks through components of reacting functions. we can also call hooks through custom hooks.
    • Hooks State

Hooks state is a new approach to defining the state in the React Application. By using “useState()” function, Hooks set and fetches the state. Through the following example, we can learn more about Hook State.

The above code gives a stateful value and a method to upgrade it. In the primary render, the value of the first parameter “Initial state” is the same as the returned state “state”. We use “setState” for updating the state.

React Hooks Tutorial - Hooks State

In the above code, we invoke “useState” in a “function”  component to include a local state in the function. We send only the “initial state”  parameter to “useState”.

 MindMajix YouTube Channel

Effect Hooks

The Hooks Effect enables us to conduct collateral effects within the components function. The Hooks Effect will not use the lifecycle methods of the components, and these methods exist in the class components. Hooks Effect is similar to componentDidUpdate(), componentDidMount() lifecycle methods.

React Hooks Tutorial -  Hooks Effect

In the above code, we invoke “useEffect” to inform the React to execute the “effect” method after reddening the modifications in the DOM. As we declare the effects in a component, the effects can use the state and props. React implements the effects after each render. Effects may also define how to do “clean up”.

Side effects contain usual properties that every web application have to conduct, like:

  • DOM Updation

  • Consuming and Retrieving data from an API Server.

  • Establishing Subscription 

Side Effects

we categorize side effects into two types:

  • Effects with Cleanup

After updating the DOM, we have to clean up some effects. For example, when we need to establish a subscription for any explicit data source, it is essential to clean up the memory to ensure that there is no memory leak.

  • Effects without Cleanup

We use Effects without Cleanup in effect that does not obstruct the browser in screen updation. Examples of Effects that do not need cleanup are Network requests, Manual DOM mutations, etc.

Custom Hooks

Custom Hook is called a Javascript function. We start the name of the custom hook with “use”, and through “use” we can invoke other hooks. By using “use” in the name of the custom, hook indicates that the custom hook obeys the hook's rules. Developing custom hooks enables us to pull component logic inside the recyclable functions.

Related Article: React Hooks Interview Questions

Creating Own Hook

By creating our hook, we can fetch component logic inside the reusable function. 

We can create our hook by using state hooks or Effect Hooks. In the below conversation application, we can see Effect Hook. In this application, we can check whether the friend is offline or online:

React Hooks Tutorial - Creating Own Hook

If the application also has a contact list and we want to display the names of the contacts with green color:

React Hooks Tutorial - Creating Own Hook

We can share the logic between “FriendListen” and “FriendStatus”

React Hooks API

We can classify the Inbuilt hooks into two parts, they are:

Basic Hooks

  • useEffect

  • useState

  • use context

Additional Hooks

  • use callback

  • useMemo

  • useRef

  • useDebugValue

  • useReducer

  • useLayoutEffect

  • useImperativeHandle

#Basic Hooks

1. useEffect

The “useEffect” API receives a method or a function that comprises essential code. We cannot include the side effects like subscriptions, mutations, logging in the function body, so we use “useEffect” to run those side effects.

2. useContext

The “useContext” API receives a context object and gives the present value of the context. By using the “value” prop, we can evaluate the present context value.

#Additional Hooks

Additional Hooks are modifications of the Basic Hooks, and we require them for particular edge cases.

1. useReducer

We use “useReducer” as a substitute to “useState”. We use “useReduce” when the state logic comprises multiple values. It returns a dispatch method coupled with the present state.

2. use callback

It gives a “memorized” callback.

3. useMemo

It sends the group(array) of dependencies and the “create” method. It gives a “memorized” callback. “useMemo” will recalculate the memorized value. 

4. useRef

This API yields an object of mutable reference, and we initialize the “.current” property of the object to the sent argument. We use “useRef” for accessing the child effectively.

5. useImperativeHandle

This API personalizes the value of the instance and that value is revealed to the parent components while using “ref”. We use “useImperativeHandle” with “forwardRef”.

6. useLayoutEffect

The sign of this API is similar to “useLayoutEffect”. We use this API for reading the Layout from the DOM.

7 useDebugValue

We use “useDebugValue” for displaying the label to Custom Hooks that is present in the React DevTools.

React Hooks Counter

In React Hooks, we use counters to increment or decrement the values. In the following React Hooks, we display votes to count. By using the clicks up/down, we can decrement or increment the vote count, and we invoke API to mend the votes count inside the database. 

React Hooks Tutorial  React hooks Counter

In React Hooks, we have a “use counter” API. The syntax of “use counter” API is as follows:

use counter(initialValue, options)

The initialValue indicates the counter’s initial value. Options indicate Counter’s options.

React Hooks Tutorial - React Hooks Counter

In the above code, we can see the creation of the counter by using “useState” API. By using the “useEffect” API also, we can implement the counter.

React Hooks Props

In React Hooks, we use props for sharing the logic throughout the components. A component can represent the UI to the other components. We use props for sharing the code among the components. In the following code, we can see how we pass the props to a state through “useState” Hooks.

React Hooks Tutorial - React hooks Props

For useState, props act as “initialState”. Even if the props get changed, the state remains the same. In the below, we can see it

React Hooks Tutorial - React Hooks Props

After pressing the button, we can see that the props will not change the profile.

Synching Props to State in React Hooks

Every Time Props change, we fix the state in the use effect

Therefore, we modify the state in the use effect, every time props get changed. useEffect manages the side effects.

React Hooks VS Redux

#React Hooks

React Hooks allows you to utilize React Lifecycle and state characteristics excluding the life cycle methods of React Component. 

The main advantages of react hooks are:

  1. Through React Hooks, we can use hook and state inside the lifecycle of the component without implementing the class.

  2. We can share the recyclable behaviors without depending on the component implementation.

#Redux

Redux is a foreseeable state-handling architecture and library that incorporates React. 

The advantages of Redux are as follows:

  1. Imperative state resolution

  2. Business State

  3. Through Side-effects, we can handle states separately.

  4. We can share the state simply among different components. 

When to use Hooks

We will use hooks, when the application contains a single view, does not load or save state, and no asynchronous input or output. When the component 

  1. Do not use the network.

  2. Do not load or save state.

  3. Require few transitory native component states.

When to use Redux

We can use Redux, when the components

  1. Use device APIs or network.

  2. Load or save state.

  3. Processes with data processing or business logic.

Conclusion

React Hooks is the latest feature that is included in the React 16.8 edition. Through React Hooks, we can develop a function component without transforming it into a class. I hope this article provides you with the required information about React Hooks. 

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
React JS TrainingMar 30 to Apr 14View Details
React JS TrainingApr 02 to Apr 17View Details
React JS TrainingApr 06 to Apr 21View Details
React JS TrainingApr 09 to Apr 24View Details
Last updated: 03 Apr 2023
About Author

Viswanath is a passionate content writer of Mindmajix. He has expertise in Trending Domains like Data Science, Artificial Intelligence, Machine Learning, Blockchain, etc. His articles help the learners to get insights about the Domain. You can reach him on Linkedin

read more
Recommended Courses

1 / 15