DEV Community

Cover image for React.js Hooks: A Quick Guide
Pulkit Gupta
Pulkit Gupta

Posted on

React.js Hooks: A Quick Guide

As developers, we're constantly looking for ways to build cleaner, more efficient, and more modular code. React, a popular JavaScript library for building user interfaces, has recently introduced a game-changing feature called Hooks. In this blog post, we'll dive into the world of React Hooks, understand their purpose, and learn how to use them with real-life examples. So, let's get hooked on Hooks!

What are React Hooks?

React Hooks are a set of functions that allow us to "hook" into React state and lifecycle features from function components. They were introduced in React 16.8 to enable developers to write cleaner and more reusable code by eliminating the need for classes and simplifying complex components. Some of the most common Hooks are useState, useEffect, and useContext.

*1. useState *

The useState Hook allows us to add state to our functional components. It's a great replacement for the old setState method in class components.

Example:

import React, { useState } from 'react';  

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

  return (  
    <div>  
      <p>clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  

export default Counter;  
Enter fullscreen mode Exit fullscreen mode

In this example, we create a simple counter component. We use the useState Hook to initialize the count state variable to 0 and provide a setCount function to update the state. When the button is clicked, the setCount function is called to increment the count by 1.

2. useEffect

The useEffect Hook allows us to perform side effects, like data fetching or updating the DOM, in our functional components. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

Example:

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

function User({ userId }) {  
  const [user, setUser] = useState(null);  

  useEffect(() => {  
    const fetchUser = async () => {  
      const response = await fetch(`https://api.example.com/users/${userId}`);  
      const userData = await response.json();  
      setUser(userData);  
    };  

    fetchUser();  
  }, [userId]);  

  return (  
    <div>  
      {user ? <p>{user.name}</p> : <p>Loading...</p>}  
    </div>  
  );  
}  

export default User;  
Enter fullscreen mode Exit fullscreen mode

In this example, we create a User component that fetches a user's data based on their userId. We use the useEffect Hook to make an API call when the component mounts or when the userId changes. The useEffect Hook takes two arguments: a function to perform the side effect and an array of dependencies. In this case, the dependency is the userId.

3. useContext

The useContext Hook allows us to access the value of a given context without using the traditional Context.Consumer component. It simplifies the process of retrieving context values in our components.

Example:

import React, { useContext } from 'react';  
import { ThemeContext } from './ThemeContext';  

function ThemedButton() {  
  const theme = useContext(ThemeContext);  

  return (  
    <button style={{ background: theme.background, color: theme.foreground }}>  
      I am a themed button!  
    </button>  
  );  
}  

export default ThemedButton;  
Enter fullscreen mode Exit fullscreen mode

In this example, we create a ThemedButton component that uses the useContext Hook to access the theme values from a ThemeContext. We then apply the theme's background and foreground colors to the button's style.

Conclusion:

React Hooks have truly revolutionized the way we build modern web applications. By understanding and implementing Hooks like useState, useEffect, and useContext, we can write cleaner, more efficient, and more modular code. So go ahead, give Hooks a try, and watch our React development skills soar to new heights

In Next Blog, I'll cover more hooks with proper examples. Stay tuned.

Top comments (2)

Collapse
 
lotfijb profile image
Lotfi Jebali

Well explained, thanks for sharing

Collapse
 
anxbt profile image
Anubrat Sahoo

i cpy pasted ur code in App.js but the in the useContext there is a error in "'./ThemeContext'; ".