The official launch of React 16.8 took place in early February, which came with a new API that enables state and other capabilities to be used in React without developing a class. Hooks is the name of this additional API, which is growing in popularity throughout the React ecosystem, spanning open-source projects to being employed in live apps. Hooks are the functions that allow function components to "hook into" state and lifecycle elements of the React framework. Since Hooks are backward-compatible, they don't include any fundamental modifications. It also doesn't take the place of your understanding of React ideas. Let us dive deeper into the world of React Hooks.
React Hooks are built-in features that let developers utilize state & lifecycle methods inside of functional components. Since they cooperate with existing code, they are simple to integrate into a codebase. Hooks were advertised to the general public as allowing developers to leverage state in functional components, but they are actually much more potent than that. They make it possible for React developers to gain these advantages:
React Hooks give developers the ability to leverage functional components for nearly all of their needs, from UI rendering to handling data and logic.
We will now look into some reasons why you should consider using React Hooks:
Hooks are comparable to JavaScript functions, however, when utilizing them, you must adhere to these two guidelines. All stateful logic in a component is guaranteed to be transparent in its source code by the hooks rule. They are as follows:
To gain in-depth knowledge with practical experience in React Js, Then explore HKR's React JS Training
The following commands must be entered in order to use React Hooks:
$ npm install [email protected] --save
$ npm install [email protected] --save
The aforementioned command will install the most recent alpha versions of React and React-DOM that enable React Hooks. Verify the package. The React and React-DOM dependencies are listed in the JSON file as follows.
"react": "^16.8.0-alpha.1",
"react-dom": "^16.8.0-alpha.1",
Without having to change a functional component into a class component, React developers can update, handle, and modify the state inside of it using the useState() hook. Let us use an example:
function App() {
const [age, setAge] = useState(19);
const handleClick = () => setAge(age + 1)
return
<div>
Hi, My age is {age} years
<div>
<button onClick={handleClick}>Increase my age! </button>
</div>
</div>
}
As you may have seen, our component lacks the complexity of a class component and appears to be rather straightforward, concise, and functional.
The two variables in the array can be given names by using JavaScript's array destructuring in the useState() hook, which takes a starting state as an argument before returning. The first variable represents the actual state, and the second is a function that can be used to provide a new state in order to update the first variable.
Output: Hi, My age is 19 years “Increase My age”
The state of the age will modify when you click the "Increase my Age" button, and the component will function similarly to a class component with state as a result.
We can carry out side effects (an action) in the function components thanks to the Effect Hook. It does not use the lifecycle methods for components found in the class components. In other words, componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle functions are comparable to Effects Hooks.
Most online applications need to execute certain functions that side effects have in common, such as:
Let's examine the Hook Effect using the following illustration.
import React, { useState, useEffect } from 'react';
function CounterExample() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default CounterExample;
There are 2 kinds of side effects in the React component:
A unique JavaScript function is called a hook. Custom Hooks have names that begin with "use," which can be used to summon other Hooks. A regular function is the same as a custom Hook, and the term "use" at the beginning indicates that the function abides by the rules of hooks. You can convert component logic into functions that can be reused by creating unique Hooks.
Let's use the example below to further understand how custom Hooks function.
import React, { useState, useEffect } from 'react';
const useDocumentTitle = title => {
useEffect(() => {
document.title = title;
}, [title])
}
function CustomCounter() {
const [count, setCount] = useState(0);
const incrementCount = () => setCount(count + 1);
useDocumentTitle(`You clicked ${count} times`);
// useEffect(() => {
// document.title = `You clicked ${count} times`
// });
return (
<div>
<p>You clicked {count} times</p>
<button onClick={incrementCount}>Click me</button>
</div>
)
}
export default CustomCounter;
UseDocumentTitle is a custom Hook in the excerpt above that accepts a string of text as an argument that represents the title of the document. We call useEffect Hook inside of this Hook and set the title if the title has changed. Only if its local state differs from what we are putting in, will the second argument run that check and change the title.
The usage When you have sophisticated state-building logic, when the future state value depends on the previous value, or when the components need to be optimized, Reducer Hook is a better alternative to useState hook and is typically recommended over it.
The useReducer hook requires three arguments, including the reducer, the method to lazily load the initial state, and the reducer. The following is the syntax:
const [state, dispatch] = useReducer(reducer, initialArgs, init);
Let us take an example:
import React, { useReducer } from "react";
// Defining the initial state and the reducer
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case "add":
return state + 1;
case "subtract":
return state - 1;
case "reset":
return 0;
default:
throw new Error("Unexpected action");
}
};
const App = () => {
// Initialising useReducer hook
const [count, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h2>{count}</h2>
<button onClick={() => dispatch("add")}>
add
</button>
<button onClick={() => dispatch("subtract")}>
subtract
</button>
<button onClick={() => dispatch("reset")}>
reset
</button>
</div>
);
};
export default App;
Output:
0
“Add”
“Subtract”
“Reset”
Want to know more about React Js,visit here React Js Tutorial!
UseRef produces a ref object that is modifiable. The object has an attribute referred to as .current. The refContainer.current property retains the value. These values can be obtained through the returning object's current property. The given input initialValue, such as useRef, could be used to initialize the.current property (initialValue). The component's whole lifetime can be preserved by the object by storing a value. The following is the Syntax:
const refContainer = useRef(initialValue);
Let us take an example:
import React, {Fragment, useRef} from 'react';
function App() {
// Creating a ref object using useRef hook
const focusPoint = useRef(null);
const onClickHandler = () => {
focusPoint.current.value =
"The quick brown fox jumps over the lazy dog";
focusPoint.current.focus();
};
return (
<Fragment>
<div>
<button onClick={onClickHandler}>
ACTION
</button>
</div>
<label>
Click on the action button to
focus and populate the text.
</label><br/>
<textarea ref={focusPoint} />
</Fragment>
);
};
export default App;
Output:
In this example, the textarea is focused using the useRef hook by the onClickHandler, which is activated anytime the ACTION button is clicked. The useRef object, which was initially initialized to null and whose value is changing to the onClick event, is the focusPoint. Check out the output of the aforementioned code.
Similar in operation to the useEffect hook, the useLayoutEffect hook fires synchronously only after all DOM loading has been completed. This is helpful for both reading the layout from the DOM and for synchronously re-rendering the DOM. But we should always utilize the useEffect hook to avoid stopping the page from loading.
The componentDidMount & componentDidUpdate methods and the useLayoutEffect hook all operate during the same phase. UseLayoutEffect should only be used if useEffect is failing to get the desired outcome. The syntax for useLayoutEffect is:
useLayoutEffect()
Let us take an example:
import React, { useLayoutEffect, useState } from 'react';
const App = () => {
const [value, setValue] = useState('GFG');
useLayoutEffect(() => {
if (value === 'GFG') {
// Changing the state
setValue('GeeksForGeeks');
}
console.log('UseLayoutEffect is called with the value of ', value);
}, [value]);
return <div>{value} is the greatest portal for geeks!</div>;
};
export default App;
Use the following command to launch the program from the project's root directory:
npm start
The desired Output will then be displayed.
The hook called useMemo in React's functional component returns a value that has been memoized. Memorization is a broad term used in computer science when we don't need to recompute a function with a particular parameter the next time because it delivers the cached result. A memoized function keeps track of the outcomes for a specific set of inputs. For instance, if a function exists to add two numbers, and we pass in the parameters 1 and 2 for the first time, the function will add these two numbers and return 3, but if the same inputs are provided again, we will return the cached value, or 3, rather than performing the add function calculation once more. When the state and props of a React component remain constant and the component does not re-render, we use this idea to ensure that the component displays the same output. The useMemo hook enhances our React application's performance.
The Syntax for useMemo is:
const memoizedValue = useMemo(functionThatReturnsValue, arrayDepencies)
Let us take an example:
import React, {useState} from 'react';
function App() {
const [number, setNumber] = useState(0)
// Using useMemo
const squaredNum = useMemo(()=> {
return squareNum(number);
}, [number])
const [counter, setCounter] = useState(0);
// Change the state to the input
const onChangeHandler = (e) => {
setNumber(e.target.value);
}
// Increases the counter by 1
const counterHander = () => {
setCounter(counter + 1);
}
return (
<div className="App">
<h1>Welcome to Geeksforgeeks</h1>
<input type="number" placeholder="Enter a number"
value={number} onChange={onChangeHandler}>
</input>
<div>OUTPUT: {squaredNum}</div>
<button onClick= {counterHander}>Counter ++</button>
<div>Counter : {counter}</div>
</div>
);
}
// function to square the value
function squareNum(number){
console.log("Squaring will be done!");
return Math.pow(number, 2);
}
export default App;
The function that returns the value, squareNum, is supplied inside the useMemo in the example above, and inside the array dependencies, we have used the number because squareNum will only run when the number changes. The squareNum function does not execute again if the counter is increased but the value entered in the input field does not change.
Conclusion
We chose classes for React components because, at the time, functional components couldn't be used to construct a state or implement lifecycle methods. By providing a way to write code that is clearer, more comprehensible, adaptable, and expandable than utilizing class components without hooks, react hooks have made implementing these functionalities considerably simpler. React has become a popular front-end framework many businesses use, encouraging more developers to add it to their knowledge base.
Other Articles :
Batch starts on 5th Jun 2023, Weekday batch
Batch starts on 9th Jun 2023, Fast Track batch
Batch starts on 13th Jun 2023, Weekday batch
Never utilize early returns in your React method; instead, use Hooks at the Top level. You can guarantee that Hooks are called in the same order every time a component renders by adhering to this rule. This is what enables React to maintain Hook state appropriately between useState and useEffect calls.
Hooks were a significant advancement in React. React apps are now more powerful, easier to use, and need less coding. While there are several Hooks in existence, you definitely should be aware of the five fundamental React hooks which are: useState, useEffect, useRef, useContext, useReducer
Some of the best react courses are as follows:
Below are the 5 most important hooks:
1) useState: to manage and save data inside of specific components
2) useEffect: to carry out operations such as sending HTTP requests or utilizing a browser API
3) useRef: to refer to JSX items.
4) useContext: to retrieve data from the React Context to more quickly communicate data between components [instead of sending props]
5) useReducer: to organize data across various components and store it
While there are other hooks than just these 5, they are not as frequently used.
It is possible to divide the built-in hooks into two sections, which are given below.
Basic Hooks
Additional Hooks