React Hooks Explained

2023-07-16

React Hooks Explained

React Hooks Explained

React Hooks were introduced in React 16.8 and have revolutionized the way we write React components. They allow you to use state and other React features without writing a class.

Common Hooks

  1. useState: Allows you to add state to functional components.
  2. useEffect: Lets you perform side effects in functional components.
  3. useContext: Subscribes to React context without introducing nesting.
  4. useReducer: Manages complex state logic in functional components.

Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.

import React, { useState, useEffect } 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>
  );
}

← Back to Home