React Hooks

React Hooks

Table of contents

No heading

No headings in the article.

Introduction to React Hooks-

React Hooks are a set of functions that allow you to use state and other React features in functional components. Before the introduction of Hooks, React's stateful logic was handled mainly by class components. Hooks were introduced in React version 16.8 as a way to simplify the process of managing state and side effects in functional components.

Most commonly used Hooks are-

There are several built-in Hooks in React that can be used for different purposes. The most commonly used Hooks are:

  1. useState(): This Hook allows you to use state in a functional component. It returns an array with two elements: the current state value and a function to update the state. Here is an example:
import React, { useState } from 'react';

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

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

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

In this example, we create a Counter component that manages a count state using the useState() Hook.We use array destructuring to assign these values to variables named count and setCount.

We define an increment function that updates the count state by calling setCount() with the new value.

In the return statement, we render the current count value and a button that calls the increment function when clicked.

That's a basic example of how to use the useState() Hook to manage state in a functional component in React.

  1. useEffect(): This Hook allows you to perform side effects in a functional component. It is similar to the lifecycle methods in class components and can be used to fetch data, manipulate the DOM, or perform any other side effect. Here is an example:
import React, { useState, useEffect } from 'react';

function Example() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading data...</p>
      )}
    </div>
  );
}

In this example, we use the useEffect() Hook to fetch data from an API when the component is mounted. We define a state variable data to store the fetched data, and use conditional rendering to display the data or a loading message while the data is being fetched.

  1. useContext()- A context in React is a way to pass data down the component tree without having to pass props manually at every level. It is useful when you have data that needs to be accessed by many components at different levels of the component tree.

    Here's an example of how to use the useContext() Hook:

    First, create a context that contains the data you want to share:

     import React from 'react';
    
     const ThemeContext = React.createContext('light');
    
     export default ThemeContext;
    

    In this example, we create a context called ThemeContext that contains a default value of 'light'. This context can be used to share the current theme of the application with all components that need it.

    Next, create a component that provides the context:

     import React from 'react';
     import ThemeContext from './ThemeContext';
    
     function App() {
       return (
         <ThemeContext.Provider value="dark">
           <div>
             <Header />
             <Main />
             <Footer />
           </div>
         </ThemeContext.Provider>
       );
     }
    
     export default App;
    

    In this example, we wrap the Header, Main, and Footer components in the ThemeContext.Provider component, which provides the context to these components and their children.

    Finally, create a component that consumes the context:

     import React, { useContext } from 'react';
     import ThemeContext from './ThemeContext';
    
     function Header() {
       const theme = useContext(ThemeContext);
    
       return (
         <header style={{ backgroundColor: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black' }}>
           <h1>Header</h1>
         </header>
       );
     }
    
     export default Header;
    

    In this example, we use the useContext() Hook to consume the ThemeContext and access the current theme value. We use this value to style the header accordingly.

    That's a basic example of how to use the useContext() Hook to consume a context in a React component.