What is an Hook? And Important hooks in react

» What is a Hook in React?

  1. In React, a hook is a special function provided by React that allows functional components to hook into certain React features and capabilities, such as state management, lifecycle methods, context, and more.

  2. React Hooks were added to React in version 16.8.

  3. To transit from class to functional components, Hooks lets us use state and other features within functional components, i.e., without writing a class component.

  4. List of hooks used in REACT.

1. useState
2. useEffect
3. useContext
4. useRef
5. useReducer
6. useCallback
7. useMemo
8. useImperativeHandle
9. useLayoutEffect
10. useDebugValue

» useSate Hook

  1. The useState hook allows us to add state to our functional components.

  2. WHAT IS STATE?

  3. State is a way to store and manage data that can change over time and affect a component’s rendering.

  4. The useState hook is a function that we can invoke to return an array.

  5. The first value of that array is the state variable we want to use, and the second value is the function we use to update the first value.

  6. const [stateVar, updateVar] = useState(0);

» Example of useState Hook:

  1. To use the useState hook in react, we have to first import it from react.
// App.js file
import React, { useState } from 'react';
  1. Then, export a default React functional component named Counter.
export default function Counter() {
  
}
  1. useState takes an initial value (it’s 0 in this case) and returns an array with two elements: the current state (count) and a function (setCount) to update that state.
export default function Counter() {
    const [count, setCount] = useState(0);
}
  1. Then, define two event handlers, “increment” and “decrement.”

  2. These functions will be called when we click on the respective buttons to increase or decrease the count.

  3. Inside the increment functions, we use setCount to increase the count state and similarly, in the decrement function, we use setCount to decrease the count state.

export default function Counter() {
 const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };
}
  1. Then, in the return statement, here we display the current count value inside the paragraph tag. We then use two buttons, “Increment” and “Decrement”.

  2. Both the buttons have an onClick attribute that specifies a JavaScript function to be executed when the button is clicked.

import React, { useState } from 'react';

export default function Counter() {

 const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };
    return (
    <div className='App'>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

» useEffect Hook

  1. The useEffect Hook allows us to perform side effects in our components; like fetching data, and directly updating the DOM and timers.

  2. The useEffect hook will allow us to express the code that needs to be run after the component renders.

  3. useEffect accepts two arguments: a function (the effect) and an optional array of dependencies.

  4. The function or effect is executed after the component renders and after any subsequent re-renders.

  5. If we provide an empty dependency array ([]), the effect runs only after the initial render.

  6. If you specify dependencies (e.g., [dependency1, dependency2]), the effect runs whenever any of those dependencies change between renders.

» Example of useEffect Hook:

  1. To use the useEffect hook in react, we have to first import it from react.

  2. Start by importing React, useState, and useEffect hooks.

// App.js file
import React, { useState, useEffect } from "react";
  1. Inside the Counter component, we use the useState hook to declare a state variable called count. We are then initializing it with an initial value of 0. setCount function is used to update the state.
export default function Counter() {
    const [count, setCount] = useState(0);
}
  1. Then we use useEffect hook to perform side effects in our functional component. In our case, we are updating the document title based on the count state.

  2. We pass a function as the first argument to useEffect. This function will run after the initial render and whenever the dependencies that is ‘count’ in our case; change.

  3. Inside the useEffect function, we set the document title to include the current count value, which will effectively update the title to show how many times the button has been clicked.

export default function Counter() {
    
    const [count, setCount] = useState(0);
    
    useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

}
  1. Then in the return statement, we have a div with the class name “App” and a

  2. When the button is clicked, the onClick event handler is triggered, and it calls setCount to increment the count state by 1.

// Full code
import React, { useState, useEffect } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div className="App">
      <button onClick={() => setCount((prevCount) => prevCount + 1)}>
        Click {count} times{" "}
      </button>
    </div>
  );
}

» useContext Hook

  1. Context is a feature in React that allows us to pass data down the component tree without us having to mannually pass the props through each level of nesting.

  2. It’s particularly useful when you have data that needs to be shared among many components.

  3. The context is used to manage global data, like: global state, theme, services, user settings, and more.

  4. Using the context in React requires 3 simple steps: creating the context, providing the context, and consuming the context.

  5. When should we use it?

1- While working with theme data(light/dark mode) 2- Passing data deeply into the tree 3- Overriding context for a part of the tree

» Example of useContext Hook:

  1. To use the useContext hook in react, start by importing React, along with two hooks: useContext and useState
// App.js file
import React, { useContext, useState } from "react";
import "./App.css";
  1. Let’s start with Step 1: Creating a context:

  2. Here, we are creating a React context called ThemeContext using React.createContext(). This context will allow us to share and access the theme among components.

// App.js file
const ThemeContext = React.createContext();
  1. Inside the functional component: We are using the useState hook to create a state variable called theme and initialize it with the value “light.”

  2. We also define a toggleTheme function that toggles the theme between “light” and “dark” based on the current state.

export default function App() {
  const [theme, setTheme] = useState("light");

  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
  };
  1. Second step is to Provide the context:

  2. Then let’s write the return statement. Here, we provide a context value using the ThemeContext.Provider component. This context value includes the theme state and the toggleTheme function.

  3. This allows child components to access and update the theme.

  4. We are then wraping content in a

    with a class name that combines “App” with the current theme using template literals. This class name will help apply the appropriate CSS styles based on the theme.

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <div className={`App ${theme}`}>
        <MyComponent />
      </div>
    </ThemeContext.Provider>
  );
}
  1. In App.css file, add these lines:
/* Light Theme */
.App.light {
  background-color: #ffffff;
  color: #333333;
}

/* Dark Theme */
.App.dark {
  background-color: #121212;
  color: #ffffff;
}
  1. Above, we are calling My Component; so let’s declare that too. Inside this component: We use the useContext hook to access the ThemeContext and destructure the theme and toggleTheme values from the c ontext. which is our third step. Consuming the context.

  2. Then we render an h1 element rendering the current theme and a button. When we will click this button; it will call the toggleTheme function to switch between “light” and “dark” themes.

function MyComponent() {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <div>
      <h1>Current Theme: {theme}</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}
// Full Code: 
import React, { useContext, useState } from "react";
import "./App.css";


const ThemeContext = React.createContext();

export default function App() {
  const [theme, setTheme] = useState("light");

  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <div className={`App ${theme}`}>
        <MyComponent />
      </div>
    </ThemeContext.Provider>
  );
}

function MyComponent() {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <div>
      <h1>Current Theme: {theme}</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}
  1. You can also refer to react.dev documentation for this.

And That’s it! You’ve successfully learned about useState, useEffect and useContext hooks in REACT.

Thank You for reading and Happy coding!😊