Introduction
In the previous series, we learned about the basics of ReactJS in which we have gone through the concept of Props and State, Functional and Class Component, Portal and Boundaries, Fragments and Pure Components.
In this series, we are going one step ahead. We are going to learn about the concept of Hooks and why Hooks are required.
What are Hooks?
Hooks are an additional feature added in React version 16.8. It is the first release of React that supports hooks. Hooks allow us to use state and other React features without writing a class.
Why are Hooks required?
There are numerous issues that existed before the release of hooks. Some of them are,
- Use of this keyword is a must while using class component. And it is a bit different from JavaScript, so hooks provide a way to get rid of "this" keyword.
- While using class component, we need to remember to bind event handlers but that is not the case with hooks.
- While using class component, classes cannot be minified very well and don't have reliable reloading.
- Stateful component logic has no way to reuse its component.
- Using class component makes code hard to follow and maintain changes.
- While using class component complex scenarios such as data fetching, animation or event handlers do not include organizing code in one place. This is due to implementing logic in lifecycle methods. Like Data retrieval, the process should be included in componentDidMount() and componentDidUpdate() methods. Due to this reason sometimes, code cannot be broken into small components
The above problems can be resolved using hooks, hooks provide a better way to implement logic, make smaller code fragments and provide more reusability. Hooks can be implemented only in functional component they cannot be implemented the in-class component.
Important Point to remember while using Hooks
- Your application must have React version 16.8 or higher
- Hooks must be used within a functional component cannot be used within a class component.
- Hooks are completely optional, there is no compulsion for using Hooks.
- It is not required to remove class while using Hooks as Hooks cannot be implemented within a class component, but it can communicate with class component.
- Hooks are completely backward compatible, it does not involve any breaking changes.
- Hooks can be implemented within an existing application without breaking the application.
- Hooks do not require any new knowledge of React, It will reuse existing knowledge such as props, State, etc. Hooks also provide direct API to use existing React knowledge.
useState() Hook
This is the first Basic hook of ReactJs. This hook is a replacement of state which is done in class components. Just like we cannot use this.setState() in functional component in the same way we cannot use useState() hooks in functional components.
useState() provides us a way to manage state when a functional component is used.
Syntax
const[state, setState] = useState(initialState)
The useState returns a stateful value and a function to update it.
Let see an example,
First, we will create a class component that will increase value by 1 on click of a button.
Add new component MathClass.js,
- import React, { Component } from 'react'
- class MathClass extends Component {
- constructor(props) {
- super(props)
- this.state = {
- addition: 0
- }
- this.incrementValue = this.incrementValue.bind(this)
- }
- incrementValue = () => {
- this.setState({
- addition: this.state.addition + 1
- })
- }
- render() {
- return (
- <div>
- <label>Added Value is {this.state.addition}</label><br></br>
- <button onClick={this.incrementValue}>Add 1 Value</button>
- </div>
- )
- }
- }
- export default MathClass
and import this in App.js,
- import React from 'react';
- import './App.css';
- import MathClass from './components/MathClass'
- function App() {
- return (
- <div className="App">
- <MathClass></MathClass>
- </div>
- );
- }
- export default App;
This will display output as below,
On button click, it will display as,
Now we will create the same example with the help of functional component having the name as MathFunction.js,
- import React,{useState} from 'react'
- function MathFunction() {
- const[addition,setAddition] = useState(0)
- return (
- <div>
- <label>Added Value is {addition}</label><br></br>
- <button onClick={() => setAddition(addition+1)}>Add 1 Value</button>
- </div>
- )
- }
- export default MathFunction
The output will be displayed as below,
There are 3 steps to implement your addition function or class,
- Create a component (functional or class).
- Need a state property that needs to be initialized
- Require a method that will set up state property
Rules of Hooks
There are 2 important rules for using Hooks,
- Hooks should only be called at Top-level; Hooks should not be used within loops, conditions and nested function.
- React hooks should only be called from functional components. It should not be used within any regular JavaScript functions.
Summary
In this article, we have learned about what hooks are, why hooks are used, and how they can be implemented. You can download the source code attached to this article. In the next article we will go in detail about using useState() in ReactJS.