Overview of React Hooks
Hello Everyone,
In this blog, I have tried to explain react hooks, how and when using them, the rules of hooks, and finally types of hooks.
What is hooks?
Hooks are the new feature introduced in the React. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components. It does not work inside classes.
When to use Hooks?
If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component.
Rules of Hooks
Hooks are similar to JavaScript functions, but you need to follow these two rules when using them. Hooks rule ensures that all the stateful logic in a component is visible in its source code.
These rules are:
1. Only call Hooks at the top level
Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a component renders.
2. Only call Hooks from React functions
You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Hooks can also be called custom Hooks.
1. useState
Hook state is the new way of declaring a state in React app. Hook uses the useState() functional component for setting and retrieving state. Let us understand from Hook's state with the following example.
In the above example, useState is the Hook which needs to call inside a function component to add some local state to it. The useState returns a pair where the first element is the current state value/initial value, and the second one is a function which allows us to update it. After that, we will call this function from an event handler or somewhere else. The useState is similar to this.setState in class.
2. useEffect
The Effect Hook allows us to perform side effects (an action) in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.
Side effects have common features which the most web applications need to perform, such as:
Updating the DOM, Fetching and consuming data from a server API, Setting up a subscription, etc. Let us understand Hook Effect with the following example.
The above code is based on the previous example with a new feature which we set the document title to a custom message, including the number of clicks.