React Hooks With Examples

What is React Hooks?

React Hook is a feature in React (a JavaScript library for building user interfaces) that lets you "hook into" React state and lifecycle features from functional components. Hooks let you use state and other React features without writing a class component. They allow you to extract stateful logic from a component so it can be tested independently and reused.

Some of the built-in hooks include

  • useState,
  • useEffect,
  • useContext.

Now we will see sample code for each built-in hooks in React,

useState

Here's a simple example of using the useState hook in a functional component in React,

import React, { useState } from 'react';

function Example() {
  // Declare a state variable called "count" and initialize it to 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In this example, useState is called with an initial value of 0. It returns an array with two elements: the current state value (count) and a function that updates it (setCount). Whenever the button is clicked, the setCount function is called with a new value, which updates the state and causes the component to re-render.

useEffect

Here's a simple example of using the useEffect hook in a functional component in React,

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

function Example() {
  // Declare a state variable called "count" and initialize it to 0
  const [count, setCount] = useState(0);

  // The useEffect hook allows you to perform side effects in your functional components
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In this example, the useEffect hook is used to set the document title whenever the count state changes. The useEffect hook takes a function as its first argument that will be run every time the component is rendered (or re-rendered). The second argument is an array of dependencies, and it tells React when to re-run the effect. If the array is empty, the effect will only run on the mount and unmount. If it contains values, the effect will run on every render if the values have changed. In this case, we didn't include any dependencies, so the effect will only run on the mount and unmount.

useContext

Here's a simple example of using the useContext hook in a functional component in React:

import React, { useContext } from 'react';

// First, we create a context with a default value
const ThemeContext = React.createContext('light');

// Then, we use the context in a functional component
function Example() {
  const theme = useContext(ThemeContext);
  return (
    <div className={`App ${theme}`}>
      <h2>The current theme is {theme}</h2>
    </div>
  );
}

In this example, we create a context with a default value of 'light'. Then, in the Example component, we use the useContext hook to get the current theme from the context. The useContext hook returns the current value of the context, which is 'light' in this case. We can then use the theme value in our component's JSX to apply different styles based on the theme.

It's important to note that the context value must be set higher up in the component tree, usually in a parent component, so that the child components can access it.

Thanks for reading my Article.


Similar Articles