DEV Community

Cover image for Day 11: Introduction to React Hooks
Dhaval Patel
Dhaval Patel

Posted on

Day 11: Introduction to React Hooks

Introduction
Welcome to Day 11 of our 30-day blog series on React.js! Today, we'll explore React Hooks, a powerful feature introduced in React 16.8 for adding state and other React features to functional components. Hooks provide a more concise and flexible way to write components compared to class components.

What are React Hooks?
React Hooks are functions that enable functional components to use state, lifecycle methods, context, and other React features without writing a class. Hooks allow you to reuse stateful logic across multiple components, making code more modular and easier to maintain.

useState Hook
The useState Hook allows functional components to add state to their logic. It returns a stateful value and a function to update that value, similar to this.state and this.setState in class components.

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

In the above example:

  • We import the useState Hook from the React package.

  • We use array destructuring to create a state variable count and a function setCount to update the count state.

  • The initial value of count is provided as an argument to useState.

useEffect Hook
The useEffect Hook enables functional components to perform side effects, such as fetching data, subscribing to events, or updating the DOM, similar to lifecycle methods in class components.

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

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const timerID = setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);

    return () => clearInterval(timerID);
  }, []); // Empty dependency array ensures the effect runs only once on component mount

  return <div>Seconds: {seconds}</div>;
}

Enter fullscreen mode Exit fullscreen mode

In the above example:
We use the useEffect Hook to start a timer when the component mounts and clean it up when the component unmounts.

The empty dependency array [] ensures the effect runs only once when the component mounts.

React Hooks revolutionize the way we write React components by allowing functional components to use state and other React features without classes. The useState and useEffect Hooks are just the beginning, as React provides many more Hooks for various use cases.

Stay tuned for tomorrow's post, where we'll explore more advanced concepts and Hooks in React, including useContext, useMemo, and useCallback.

Top comments (0)