A way to use local state and other features without wriging a new class. React Hooks let functional components allow you to use state and lifecycle features since React 16.8. 

 

Hooks like useState, useEffect, and useContext make it easier to manage component logic without using classes, improving readability and reusability.

 

React hook types?
React has built-in and custom hooks. 

  • Basic hooks are useState(), useContext(), and useEffect(). 
  • Additional hooks include useMemo(), useRef(), and others. JavaScript's 
  • Custom Hook acts like a standard function.

 

 

useState and how does it work? 

Hook useState adds state to functional components. It returns an array with the current state and a function to update it from an initial state value. useState re-renders the component after state changes. 

 

useEffect and how does it work? 

The useEffect hook allows you to perform side effects in a functional component. Side effects include things like fetching data from an API, updating the DOM,  build up subscriptions., or subscribing to an event. 

Effects can run after render and clean up when dependencies change by combining componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

For the first argument, the useEffect hook needs a function. For the second argument, it needs a list of dependencies.

import React, { useState, useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState([]);

 import React, { useState, useEffect } from 'react';

function DataFetcher() {
 const [data, setData] = useState([]);

 useEffect(() => {
   fetch('https://api.example.com/data')
     .then(response => response.json())
     .then(data => setData(data));
 }, []);

 return (
   <ul>
     {data.map(item => (
       <li key={item.id}>{item.name}</li>
     ))}
   </ul>
 );
}

Using the setData function, we get data from an API and use it to change the state of the component.

 

useContext hook and how does it work? 

You can get to a context object in a functional component using the useContext hook. You don't have to pass props by hand when you use context to pass data down the component tree. 

import React, { useContext } from 'react';
import React, { useContext } from 'react';const ThemeContext = React.createContext('light');

function ThemeButton() {
 const theme = useContext(ThemeContext);

 return (
   <button style={{ background: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black' }}>
     Toggle Theme
   </button>
 );
}


Related Question