Show List

React Hooks

React Hooks are a feature in React that allow you to add state and other React features to functional components. Prior to React Hooks, state and other React features could only be added to class components. Hooks make it possible to reuse state logic and other logic between components, without having to write a class component.

Here's a simple example of how to use the useState hook to add state to a functional component:

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

In this example, the useState hook is imported from the react library and then used to add state to the component. The useState hook takes an initial value as its argument and returns an array with two elements - the current state value and a function to update the state. In this example, we are using destructuring assignment to extract the state value count and the function setCount from the returned array.

The component uses the state value count to display the number of times the button has been clicked. The function setCount is passed as an event handler to the onClick prop of the button, which updates the state value when the button is clicked.

Here's another example that demonstrates how to use the useEffect hook to add side effects to a functional component:

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>
  );
}

In this example, the useEffect hook is used to add a side effect to the component. The useEffect hook takes a function as its argument that contains the side effect code. In this example, the side effect updates the document title to reflect the number of times the button has been clicked.

React Hooks provide a powerful and flexible way to add state, side effects, and other logic to functional components in React. By understanding how to use React Hooks, you can write more efficient and reusable components for your React applications.


    Leave a Comment


  • captcha text