React Hooks

React Hooks are functions that allow you to use state and other React features in functional components. Introduced in React 16.8, they eliminate the need for class components and make function components more powerful.


1 useState Hook

The useState hook lets you add state to functional components. It returns an array with two elements: the current state and a function to update it.

App.js

</>
Copy
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0); // Initialize state

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;

Explanation:

  • useState(0): Initializes the state with a value of 0.
  • The value returned by useState() is stored in [count, setCount]. Therefore, count holds the current state, and setCount is the function to update it.
  • We are calling the setCount function to update the count to count+1, when the button is clicked. We pass the new value count+1 as argument to the setCount function.
  • The component re-renders whenever the state changes.

Output Video:


2 useEffect Hook

The useEffect hook allows you to perform side effects in functional components, such as data fetching, subscriptions, or directly updating the DOM.

App.js

</>
Copy
import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }, 1000);

    return () => clearInterval(interval); // Cleanup on unmount
  }, []); // Empty array ensures it runs only once

  return <h2>Elapsed Time: {seconds} seconds</h2>;
}

export default Timer;

Explanation:

  • The useEffect hook sets up a timer using setInterval.
  • The cleanup function ensures the timer is cleared when the component unmounts.
  • An empty dependency array ([]) ensures the effect runs only once.

Output Video:


3 useContext Hook

The useContext hook provides an easy way to consume context values without needing to wrap components in a Consumer.

App.js

</>
Copy
import React, { createContext, useContext } from 'react';

const UserContext = createContext();

function UserProfile() {
  const user = useContext(UserContext);
  return <h2>User: {user}</h2>;
}

function App() {
  return (
    <UserContext.Provider value="Alice">
      <UserProfile />
    </UserContext.Provider>
  );
}

export default App;

Explanation:

  • createContext: Creates a context for the user.
  • useContext: Consumes the context value without needing a wrapper component.
  • In this example, the UserProfile component dynamically displays the user’s name.

Output: