Skip to content
Home » Forum

Forum

A Guide to React Ho...
 
Notifications
Clear all

[Solved] A Guide to React Hooks in Functional Components

1 Posts
1 Users
0 Reactions
68 Views
Mark Sikaundi
(@emmanuelmark117)
Member Admin
Joined: 2 years ago
Posts: 101
Topic starter  

React hooks have transformed the way developers build applications with React by allowing the use of state and lifecycle features in functional components. This article provides a detailed overview of the most commonly used hooks and how to implement them effectively.

1. useState

Description

useState is a hook that allows you to manage state in functional components.

Usage

 
import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

2. useEffect

Description

useEffect lets you perform side effects in functional components, such as data fetching or subscriptions.

Usage

 
import React, { useEffect, useState } from "react";
function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch("https://api.example.com/data");
      const result = await response.json();
      setData(result);
    };
    fetchData();
  }, []);
} // Empty array runs effect once on mount return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; }

3. useContext

Description

useContext allows you to access the context value directly without wrapping components in a Consumer.

Usage

 
import React, { useContext } from "react";
const ThemeContext = React.createContext("light");
function ThemedComponent() {
  const theme = useContext(ThemeContext);
  return (
    <div style={{ background: theme === "dark" ? "#333" : "#FFF" }}>
      Theme is {theme}
    </div>
  );
}

// USAGE
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedComponent />
    </ThemeContext.Provider>
  );
}

4. useReducer

Description

useReducer is an alternative to useState for managing complex state logic.

Usage

 
import React, { 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 Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
      {" "}
      Count: {state.count}{" "}
      <button onClick={() => dispatch({ type: "increment" })}>Increment</button>{" "}
      <button onClick={() => dispatch({ type: "decrement" })}>Decrement</button>{" "}
    </div>
  );
}

5. useMemo

Description

useMemo memoizes a value to optimize performance and prevent unnecessary recalculations.

Usage

 
import React, { useMemo, useState } from "react";
function ExpensiveComputation({ num }) {
  const computeFactorial = (n) => {
    return n <= 0 ? 1 : n * computeFactorial(n - 1);
  };
  const factorial = useMemo(() => computeFactorial(num), [num]);
  return (
    <div>
      Factorial of {num} is {factorial}
    </div>
  );
}

6. useCallback

Description

useCallback memoizes a callback function to avoid recreating it on every render.

Usage

 
import React, { useCallback, useState } from "react";
function Counter({ onIncrement }) {
  console.log("Counter rendered");
  return <button onClick={onIncrement}>Increment</button>;
}
function App() {
  const [count, setCount] = useState(0);
  const handleIncrement = useCallback(() => {
    setCount((prev) => prev + 1);
  }, []);
  return (
    <div>
      {" "}
      <p>Count: {count}</p> <Counter onIncrement={handleIncrement} />{" "}
    </div>
  );
}

7. useRef

Description

useRef creates a mutable ref object that persists for the full lifetime of the component.

Usage

 
import React, { useRef } from "react";
function TextInput() {
  const inputRef = useRef(null);
  const focusInput = () => {
    inputRef.current.focus();
  };
  return (
    <div>
      {" "}
      <input ref={inputRef} type="text" />{" "}
      <button onClick={focusInput}>Focus Input</button>{" "}
    </div>
  );
}

8. Custom Hooks

Description

Custom hooks allow you to encapsulate reusable logic across components, enhancing code organization and reusability.

Example

 
import { useState, useEffect } from "react";
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(url);
      const result = await response.json();
      setData(result);
      setLoading(false);
    };
    fetchData();
  }, [url]);
  return { data, loading };
} // Usage in a component function App() { const { data, loading } = useFetch('https://api.example.com/data'); if (loading) return <div>Loading...</div>; return <div>{JSON.stringify(data)}</div>; }

Conclusion

React hooks offer powerful tools for managing state, side effects, and more in functional components. They encourage reusability and organization, simplifying the development process and enhancing code maintainability. By leveraging these hooks, you can create efficient and scalable React applications. If you have any questions or want to explore specific hooks further, feel free to drop a comment here.


   
Quote
Share: