DEV Community

Soham
Soham

Posted on

React Hooks

React is a JavaScript library for building user interfaces. It was developed by Facebook, and is often used for building single-page applications and mobile applications.

In React, a "hook" is a special function that allows you to "hook into" React features from your functional components. Hooks were introduced in React 16.8 as a way to add state and other react features to functional components.

There are several types of hooks in React, including:

useState: This hook allows you to add state to a functional component. It returns an array with two elements: the current state value and a function to update the state.


import { useState } from 'react';

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

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

useEffect: This hook allows you to perform side effects in functional components. It takes a function as an argument, which will be run after the component renders. You can also specify a list of dependencies as a second argument, which will determine when the effect is run. If the dependencies haven't changed, the effect will not be run.

import { useEffect, useState } from 'react';

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

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

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

useContext: This hook allows you to access the React context in a functional component. The context is an object that is passed down the component tree, and can be used to share values between components without having to pass props down manually.

import { useContext } from 'react';

const MyContext = React.createContext();

function Example() {
  const value = useContext(MyContext);

  return <div>{value}</div>;
}
Enter fullscreen mode Exit fullscreen mode

useReducer: This hook is similar to useState, but it allows you to manage complex state objects and update them using reducer functions. It takes a reducer function and an initial state as arguments, and returns the current state and a dispatch function that can be used to update the state.

import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)