React Hooks were introduced in React 16.8 as a means to use state and other React features without having to write a class. Hooks are functions that let us hook into React state and lifecycle features from function components.
There are many built-in hooks in React, such as useState, useEffect, useContext, useReducer, and useRef.
Here are a couple of examples of how to use them:
1. useState: This hook is used for adding state to functional components.
```
import React, { useState } from ‘react’;
function Example() { // Declare a new state variable, which we’ll call “count“ const [count, setCount] = useState(0);
return (You clicked {count} times
1. useEffect: This hook is used to perform side effects in function components. It is similar to `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` combined in class components.
```
import React, { useState, useEffect } from ‘react’;
function Example() { 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 (You clicked {count} times
Important rules when using hooks:
i) Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
ii) Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions.