Built-in React Hooks

React provides several built-in Hooks that you can use to manage state, handle side effects, and more. Here are some of the most commonly used React Hooks:

useState Hook

The useState Hook allows you to add state to your functional components. Here's an example:

import { useState } from 'react'

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

  function handleClick() {
    setCount(count + 1)
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  )
}

In this example, we initialize the count state variable to 0 and get a setCount function from useState that we can use to update the count variable. Inside our component, we render the current value of count and a button that calls the handleClick function when clicked.

useEffect Hook

The useEffect Hook allows you to handle side effects in your functional components, such as fetching data from an API or subscribing to a WebSocket. Here's an example:

import { useState, useEffect } from 'react'

function MyComponent() {
  const [data, setData] = useState(null)

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://api.example.com/data')
      const json = await response.json()
      setData(json)
    }

    fetchData()
  }, [])

  if (!data) {
    return <div>Loading...</div>
  }

  return (
    <div>
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  )
}

In this example, we use useState to add a data state variable to our component. We then use useEffect to fetch data from an API when the component mounts. We pass an empty array ([]) as the second argument to useEffect, which tells React to only call our effect once when the component mounts. Finally, we render the data we fetched from the API.

useRef Hook

The useRef Hook allows you to create a mutable reference to a value that persists across renders. Here's an example:

import { useRef } from 'react'

function MyComponent() {
  const inputRef = useRef(null)

  function handleClick() {
    inputRef.current.focus()
  }

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus</button>
    </div>
  )
}

In this example, we use useRef to create a reference to an input element. We then use the handleClick function to call the focus method on the inputRef.current value when the button is clicked.

useCallback Hook

The useCallback Hook allows you to memoize a function so that it is only re-created when its dependencies change. Here's an example:

import { useState, useCallback } from 'react'

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

  const handleClick = useCallback(() => {
    setCount(count + 1)
  }, [count])

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  )
}

In this example, we use useCallback to memoize the handleClick function. We pass the count variable as a dependency to useCallback, which ensures that the function is only re-created when count changes.

useMemo Hook

The useMemo Hook allows you to memoize a value so that it is only re-computed when its dependencies change. Here's an example:

import { useMemo } from 'react'

function MyComponent() {
  const numbers = [1, 2, 3, 4, 5]

  const sum = useMemo(() => {
    return numbers.reduce((acc, curr) => acc + curr, 0)
  }, [numbers])

  return (
    <div>
      <p>Sum: {sum}</p>
    </div>
  )
}

In this example, we use useMemo to memoize the sum variable. We pass the numbers array as a dependency to useMemo, which ensures that the sum is only re-computed when the numbers array changes.

useContext Hook

The useContext Hook allows you to consume a context value created by the React.createContext function. Here's an example:

import React, { useContext } from 'react'

const ThemeContext = React.createContext('light')

function MyComponent() {
  const theme = useContext(ThemeContext)

  return (
    <div>
      <p>Current theme: {theme}</p>
    </div>
  )
}

In this example, we create a ThemeContext using the React.createContext function. We then use the useContext Hook to consume the current theme value from the ThemeContext and render it.

useReducer Hook

The useReducer Hook allows you to manage state in your functional components using a reducer function. Here's an example:

import { useReducer } from 'react'

const initialState = { count: 0 }

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 MyComponent() {
  const [state, dispatch] = useReducer(reducer, initialState)

  function handleIncrement() {
    dispatch({ type: 'increment' })
  }

  function handleDecrement() {
    dispatch({ type: 'decrement' })
  }

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={handleIncrement}>Increment</button>
      <button onClick={handleDecrement}>Decrement</button>
    </div>
  )
}

In this example, we define an initialState and a reducer function that takes a state and an action and returns a new state based on the action type. We then use useReducer to create a state variable and a dispatch function that we can use to update the state. Inside our component, we render the current value of state.count and two buttons that call the handleIncrement and handleDecrement functions when clicked, respectively.