DEV Community

Erasmus Kotoka
Erasmus Kotoka

Posted on

Deep Dive into React Hooks: useState, useEffect, and Custom Hooks

let talk about

Deep Dive into React Hooks: useState, useEffect, and Custom Hooks

Introduction:

React Hooks provide a powerful way to manage state and side effects in functional components.

In this post, we’ll explore three essential hooks—useState, useEffect, and Custom Hooks—and how they can enhance your React applications.

  1. useState: Managing State in Functional Components
  • useState is the most basic hook for state management in React.

  • Syntax: const [state, setState] = useState(initialValue);

  • Key Points:

    • Allows functional components to have internal state.
    • You can pass an initial value or a function to compute the initial state.
    • The setState function allows updating the state, triggering a re-render.
  • Example:


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

Enter fullscreen mode Exit fullscreen mode
  1. useEffect: Handling Side Effects
  • useEffect is used to handle side effects in your components, such as data fetching, subscriptions, and manually changing the DOM.

  • Syntax:


 useEffect(() => {

  // Effect code

  return () => {

   // Cleanup (optional)

  };

 }, [dependencies]);

Enter fullscreen mode Exit fullscreen mode
  • Key Points:

    • By default, useEffect runs after every render.
    • You can control when it runs by passing dependencies as the second argument.
    • For one-time effects (like componentDidMount), pass an empty array [].
  • Example: Fetching data when a component mounts.


 useEffect(() => {

  fetchData();

 }, []);

Enter fullscreen mode Exit fullscreen mode
  1. Custom Hooks: Reusable Logic
  • Custom hooks allow you to extract and reuse logic across multiple components.

  • Why Custom Hooks?

    • They help avoid code duplication.
    • Promote reusability and cleaner component code.
  • Syntax:


 const useCustomHook = () => {

  // Custom logic

  return [state, handler];

 };

Enter fullscreen mode Exit fullscreen mode
  • Example: A custom hook to manage form inputs.

 const useInput = (initialValue) => {

  const [value, setValue] = useState(initialValue);

  const handleChange = (e) => setValue(e.target.value);

  return [value, handleChange];

 };

Enter fullscreen mode Exit fullscreen mode

Conclusion:

React Hooks like useState and useEffect simplify state and side-effect management in functional components.

Custom Hooks take it a step further by promoting reusability and clean code practices. Mastering these hooks is key to building efficient React apps.

CODEWith #KOToka

Top comments (0)