React Hooks.

React Hooks.

What are the react Hooks and their use cases.

React Hooks are introduced react 16 with functional component. There are multiple built in react Hooks which we commonly used during application. Let's understand built-in React hook :

  1. useState Hook

useState is most commonly used hook in a react application. It is used to handle the state locally in a component. A state in react application is referred as the current view or state of page or UI.

import {useState} from "react";
export default function My component(){
   const [count,setCount] = useState(0);
return (
       <>
       <div>{count}</div>
       <button onClick={()=>{setCount(count+1)}}>Increment</button>
       </>
   )
}
  1. useEffect hook

useEffect was introduced in react js 16 in the place of componentDidMount() which is used to run a function or set a state when a component renders. useEffect mostly used when We have to fetch data from api and render it to the page whenever component renders. useEffect contains two things first is callback function which should run before rendering the component and second is dependency array which defines when should we re run the useEffect hook. For initial rendering we use empty array

import {useEffect} from "react";
export default My component(){

useEffect(()=>{
  function fetchdata(`url`)
  .then((response)=> response.json())
  .then(data => console.log(data));

  fetchdata ();
},[])

 return (
    <>
      <div>Open Chrome devtool to see the logs</div>
    </>
  )
}
  1. useRef Hook

useRef hook is used to give the reference of value that does not needed for rendering. useRef returns a ref object with a single current property initially set to the initial value you provided.

On the next renders, useRef will return the same object. You can change its current property to store information and read it later. This might remind you of state, but there is an important difference.

Changing a ref does not trigger a re-render. This means refs are perfect for storing information that doesn’t affect the visual output of your component. For example, if you need to store an interval ID and retrieve it later, you can put it in a ref. To update the value inside the ref, you need to manually change its current property

import { useRef } from 'react';

export default function Counter() {
  let ref = useRef(0);

  function handleClick() {
    ref.current = ref.current + 1;
    alert('You clicked ' + ref.current + ' times!');
  }

  return (
    <button onClick={handleClick}>
      Click me!
    </button>
  );
}
  1. useCallback Hook

useCallback is react hook that cache the function which is expensive function between re-renders.

import { useCallback } from 'react';
import ShippingForm from './ShippingForm.js';

export default function ProductPage({ productId, referrer, theme }) {
  const handleSubmit = useCallback((orderDetails) => {
    post('/product/' + productId + '/buy', {
      referrer,
      orderDetails,
    });
  }, [productId, referrer]);

  return (
    <div className={theme}>
      <ShippingForm onSubmit={handleSubmit} />
    </div>
  );
}

function post(url, data) {
  // Imagine this sends a request...
  console.log('POST /' + url);
  console.log(data);
}

In this example, the ShippingForm component is artificially slowed down so that you can see what happens when a React component you’re rendering is genuinely slow. Try incrementing the counter and toggling the theme.

Incrementing the counter feels slow because it forces the slowed down ShippingForm to re-render. That’s expected because the counter has changed, and so you need to reflect the user’s new choice on the screen.

Next, try toggling the theme. Thanks to useCallback together with memo, it’s fast despite the artificial slowdown! ShippingForm skipped re-rendering because the handleSubmit function has not changed. The handleSubmit function has not changed because both productId and referrer (your useCallback dependencies) haven’t changed since last render.