Skip to main content

Archive

Show more

Hooks In React.js

React Hooks

React Hooks are functions that enable functional components to use state and other React features without writing a class. Introduced in React 16.8, Hooks provide a more concise and flexible way to manage component logic and state. Here's an overview of React Hooks:


1. useState Hook

The useState Hook allows functional components to manage local state. It returns a stateful value and a function to update that value, providing a simpler alternative to class-based state.

Example:

import React, { useState } from 'react';

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

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

2. useEffect Hook

The useEffect Hook performs side effects in functional components. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

Example:

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

3. useContext Hook

The useContext Hook provides a way to consume context in functional components. It allows components to access context values without nesting.

Example:

import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button style={{ background: theme.background, color: theme.foreground }}>I am styled by theme context!</button>;
}

4. Custom Hooks

Custom Hooks are JavaScript functions that utilize React Hooks internally. They allow developers to reuse stateful logic across components, promoting code reuse and modularity.

Example:

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

function useDocumentTitle(title) {
  useEffect(() => {
    document.title = title;
  }, [title]);
}

function Example() {
  const [count, setCount] = useState(0);
  useDocumentTitle(`You clicked ${count} times`);

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

5. Conclusion

React Hooks revolutionize functional components by enabling them to use state and other React features. By leveraging Hooks such as useState, useEffect, useContext, and creating custom Hooks, developers can write more concise, readable, and reusable code in their React applications.

Comments