DEV Community

V Sai Harsha
V Sai Harsha

Posted on

Learn Basic Hooks in React

Introduction

React Hooks revolutionized state management and side effects in functional components. They allow you to manage component state and lifecycle features without writing class components. In this comprehensive guide, we will explore the most commonly used React Hooks and even build a custom hook from scratch.

Understanding React Hooks

React Hooks are functions that let you "hook into" React state and lifecycle features from function components. The most commonly used hooks are:

1. useState

useState enables functional components to manage state. It takes an initial state as an argument and returns an array with the current state and a function to update it.

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

2. useEffect

useEffect allows you to perform side effects in your functional components. It runs after the component renders and can mimic componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods.

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

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

3. useContext

useContext allows you to access the context directly within a functional component. It's particularly useful for managing application-wide state.

import React, { useContext } from 'react';

const MyContext = React.createContext();

function Example() {
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>;
}
Enter fullscreen mode Exit fullscreen mode

Building a Custom Hook

Custom hooks allow you to reuse stateful logic across multiple components. Let's create a custom hook for handling form input:

import { useState } from 'react';

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

  function handleChange(e) {
    setValue(e.target.value);
  }

  return {
    value,
    onChange: handleChange,
  };
}
Enter fullscreen mode Exit fullscreen mode

Now, you can use this custom hook in your components:

function MyForm() {
  const username = useFormInput('');
  const password = useFormInput('');

  function handleSubmit() {
    console.log('Username:', username.value);
    console.log('Password:', password.value);
  }

  return (
    <div>
      <input type="text" {...username} placeholder="Username" />
      <input type="password" {...password} placeholder="Password" />
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Custom hooks make it easy to share logic and stateful behaviour between components while keeping your code clean and maintainable.

Conclusion

React Hooks have transformed the way we work with state and side effects in functional components. Understanding and using hooks like useState, useEffect, and useContext allows you to build more modular and efficient React applications.

Additionally, creating custom hooks empowers you to encapsulate and share complex logic across your components, enhancing code reusability and maintainability.

By mastering React Hooks and custom hooks, you'll be well-equipped to create powerful and efficient React applications.

Top comments (0)