In this React Hooks Tutorial, we will learn all the essential concepts of React Hooks.
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.
Related Article: Introduction to ReactJS
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.
1. 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.
2. Invoking Hooks through React Functions
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.
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”.
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.
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:
Consuming and Retrieving data from an API Server.
we categorize side effects into two types:
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.
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.
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:
If the application also has a contact list and we want to display the names of the contacts with green color:
We can share the logic between “FriendListen” and “FriendStatus”
We can classify the Inbuilt hooks into two parts, they are:
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.
The “useContext” API receives a context object and gives the present value of the context. By using “value” prop, we can evaluate the present context value.
Additional Hooks are modifications of the Basic Hooks, and we require them for particular edge cases.
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.
It gives a “memorized” callback.
It sends the group(array) of dependencies and the “create” method. It gives a “memorized” callback. “useMemo” will recalculate the memorized value.
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.
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”.
The sign of this API is similar to “useLayoutEffect”. We use this API for reading the Layout from the DOM.
We use “useDebugValue” for displaying the label to Custom Hooks that is present in the React DevTools.
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.
In React Hooks, we have a “useCounter” API. The syntax of “useCounter” API is as follows:
use counter(initialValue, options)
The initialValue indicates the counter’s initial value. Options indicate Counter’s options.
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.
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.
For useState, props act as “initialState”. Even if the props get changed, the state remains the same. In the below, we can see it
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 useEffect
Therefore, we modify the state in the useEffect, every time props get changed. useEffect manages the side effects.
React Hooks allows you to utilize React Lifecycle and state characteristics excluding life cycle methods of React Component.
The main advantages of react hooks are:
Through React Hooks, we can use hook and state inside the lifecycle of the component without implementing the class.
We can share the recyclable behaviors without depending on the component implementation.
Redux is a foreseeable state handling architecture and library that incorporates React.
The advantages of Redux are as follows:
Imperative state resolution
Through Side-effects, we can handle states separately.
We can share the state simply among different components.
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
Do not use the network.
Do not load or save state.
Require few transitory native component states.
We can use Redux, when the components
Use device APIs or network.
Load or save state.
Processes with data processing or business logic.
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.
If you have any queries, let us know by commenting in the below section.