What is Hooks in React JS?

#hooks

#react hook

Hooks in React are special functions that allow you to use state and other React features in functional components. Introduced in React 16.8, hooks provide a more concise and powerful way to manage component state, lifecycle, and side effects compared to class components.

Key Hooks in React


1. `useState`

The useState hook allows you to add `state` to functional components.

Example: `useState`

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

export default Counter;

In this example:

  • `useState(0)` initializes a state variable `count` with the value `0`.
  • `setCount` is a function that updates the state.

2. `useEffect`

The `useEffect` hook allows you to perform side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.

Example: `useEffect`

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

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

  useEffect(() => {
    const timer = setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);

    // Cleanup function to clear the timer
    return () => clearInterval(timer);
  }, []);

  return <h1>{count}</h1>;
}

export default Timer;

In this example:

  • `useEffect` runs the side effect (setting an interval) after the component renders.
  • The cleanup function clears the interval when the component unmounts.

3. `useContext`

The `useContext` hook allows you to use the React Context API to share state across components without prop drilling.

Example: `useContext`

import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext();

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

function ThemedButton() {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Toggle Theme
    </button>
  );
}

function App() {
  return (
    <ThemeProvider>
      <ThemedButton />
    </ThemeProvider>
  );
}

export default App;

In this example:

  • `ThemeContext` is created and provided by the `ThemeProvider`.
  • `ThemedButton` uses useContext to access the `theme` value and `setTheme` function.

4. `useReducer`

The `useReducer` hook is used for complex state logic. It's an alternative to `useState`.

Example: `useReducer`

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

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
}

export default Counter;

In this example:

  • `reducer` function manages state transitions based on the action type.
  • `useReducer` initializes the state and provides the `dispatch` function to send actions.

5. `useMemo`

The `useMemo` hook memoizes a value, computing it only when its dependencies change, improving performance.

Example: `useMemo`

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

function ExpensiveComputation({ num }) {
  const computeFactorial = n => {
    if (n <= 1) return 1;
    return n * computeFactorial(n - 1);
  };

  const factorial = useMemo(() => computeFactorial(num), [num]);

  return <div>Factorial of {num} is {factorial}</div>;
}

function App() {
  const [num, setNum] = useState(5);

  return (
    <div>
      <input type="number" value={num} onChange={e => setNum(e.target.value)} />
      <ExpensiveComputation num={num} />
    </div>
  );
}

export default App;

In this example:

  • `useMemo` calculates the factorial only when `num` changes, avoiding unnecessary recomputations.

Custom Hooks

Custom hooks allow you to encapsulate logic and reuse it across components.

Example: Custom Hook

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

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);

    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

function App() {
  const width = useWindowWidth();

  return <div>Window width: {width}</div>;
}

export default App;

In this example:

  • `useWindowWidth` is a custom hook that manages the window width state.
  • It can be reused across multiple components.

Conclusion

Hooks in React provide a powerful and flexible way to manage state, side effects, context, and more in functional components. By using hooks, you can write cleaner, more concise, and reusable code, making your components easier to understand and maintain. Understanding and effectively using hooks is essential for modern React development.

Further, if you have any questions, please visit our website, Gurulabs Website Design Agency.