What is hook?

Hooks allow function components to have access to state and other React features(eg: lifecycle methods). Because of this, class components are generally no longer needed.

Conditions for hooks
Can only be called inside React function components
Must be called at the top level of a component
Cannot be used conditionally

Types of hooks

useState hook

Usage involves declaring a state variable, and when variable is updated react will trigger a re-render.

import React, { useState } from 'react';

function ColorSelector() {
    const [color, setColor] = useState('red');              //1

    return (
        <div style={{ backgroundColor: color }}>     //3
            <p>Current Color: {color}</p>
            <button onClick={() => setColor('blue')}>Change to Blue</button>  //2
        </div>
    );
}
                
state variables

1. Creates a state variable color initially set to 'red'. setColor() is a function to update the color state variable
  When setColor() is called, React automatically re-renders the component
2. Button, onclick of button setColor() function is called, which updates the state variable
3. As state variable is called, React re-renders and background color changes to blue.

useEffect hook

What is side effect in React
In React side effect is action or operation that occurs in a component after rendering, but is not directly related to rendering the user interface.
Examples of side effects:
  Making an asynchronous request to fetch data from an API
  Changing the title of a webpage
  Setting up a subscription to an external data source
  Keeping user information
  Updating themes

useEffect manages side effects in components.

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

function DataFetcher() {
    const [data, setData] = useState(null);             //2
    
    useEffect(() => {                                   //3
        fetch('https://reactnative.dev/movies.json') //HTTP GET
        .then(response => response.json())              //4
        .then(result => setData(result));               
    }, []);                                             //3a

    return 
        <div>
            {data ? JSON.stringify(data) : 'Loading...'}
        </div>;
}
export default DataFetcher;
                
Output
{ "title":"The Basics - Networking", "description":"Your app fetched this from a remote endpoint!", "movies": [ {"id":"1","title":"Star Wars","releaseYear":"1977"}, {"id":"2","title":"Back to the Future","releaseYear":"1985"}, {"id":"3","title":"The Matrix","releaseYear":"1999"}, {"id":"4","title":"Inception","releaseYear":"2010"}, {"id":"5","title":"Interstellar","releaseYear":"2014"} ] }

1. Hooks useEffect, useState used
2. Local variable data is created
3. Inside useEffect() hook HTTP GET(fetch()) is called, on response response data is set
  a. empty dependency array [] ensures, fetch runs only once
4. .then statements:
  1st then(parses response): response is the raw HTTP response object, response.json() converts the response body to a JSON object
  2nd then(update component state): result is the parsed JSON data from the previous step, setData(result) updates the component's state with the fetched data


Code without useEffect() = endless re-render

import React, { useState, useEffect } from 'react';
function DataFetcher() {
    const [data, setData] = useState(null);
    
        fetch('https://reactnative.dev/movies.json')
        .then(response => response.json())
        .then(result => setData(result));

    return 
        <div>
            {data ? JSON.stringify(data) : 'Loading...'}
        </div>;
}
export default DataFetcher;
                    
if fetch() is called without useEffect() following will happen:
fetch() is called > setData() updates data variable > This triggers another component render > fetch() runs again > Creates an endless cycle of re-renders