Enable Dark Mode!
what-are-popular-hooks-and-how-to-use-them.jpg
By: Mohd Midhlaj

What are Popular Hooks & How to Use Them

Technical

React Hooks were introduced in React 16.8 and revolutionized the way we build user interfaces. They eliminate the need for classes by providing a way to include state and other React functions in a functional context. This detailed guide will take an in-depth look at popular React Hooks, examining their functionality, usability, and benefits. Finally, you'll gain a better understanding of how to use Hooks to create flexible and customizable React applications.

1. useState: Managing Component State with Ease

The useState hook allows functional components to have their own state. It simplifies the process of managing and updating state variables, eliminating the need for class components. useState allows you to declare a state variable and its initial value within a function component. React then returns an array containing the current state values ??and functions to update those values.

This dynamic duo enables seamless state management in functional components.

Example:

import React, { useState } from 'react';
const Counter = () => {
  // Declare a state variable 'count' with an initial value of 0
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

* We import the useState hook from the 'react' package.

* Inside the Counter component, we declare a state variable count using useState(0), with an initial value of 0.

* The setCount function allows us to update the count state variable. In the example, we increment count by 1 whenever the button is clicked, triggering a re-render and displaying the updated count.

2. useEffect: Handling Side Effects

The useEffect hook is used to perform side effects in functional components, such as data fetching, subscriptions, or DOM manipulations. It takes a callback function as its first argument, which will be executed after every render. Additionally, You can choose to supply a dependency array as the second argument. This enables you to regulate when the effect will be executed by tracking changes in specific variables.

import React, { useState, useEffect } from 'react';
const Timer = () => {
  const [seconds, setSeconds] = useState(0);
  useEffect(() => {
    // Define an interval that increments the 'seconds' state variable every second
    const interval = setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);
    // Clean up the interval when the component unmounts or 'seconds' changes
    return () => clearInterval(interval);
  }, []); // Empty dependency array to run the effect only once
  return <div>Seconds: {seconds}</div>;
};

* We import the useState and useEffect hooks from the 'react' package.

* Inside the Timer component, we declare a state variable seconds and an update function setSeconds using useState(0), with an initial value of 0.

* The useEffect hook is employed to initiate an interval, which increases the value of the seconds state variable every second.

* We return a cleanup function inside the effect using clearInterval to stop the interval when the component unmounts or when seconds changes.

* The absence of a dependency array [] guarantees a singular execution of the effect, mimicking the behavior of componentDidMount.

3. useContext: Accessing Context in Functional Components

The useContext hook simplifies the consumption of Context in functional components. It takes a context object created by React.createContext() and returns the current value of the context. This eliminates the need for nested <Context.Consumer> components and provides a more straightforward approach to accessing context values.

Example

import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
const ThemeDisplay = () => {
  // Access the current theme value from the ThemeContext
  const theme = useContext(ThemeContext);
  return <div>Current Theme: {theme}</div>;
};

* We create a ThemeContext using React.createContext and provide a default value of 'light'.

* Inside the ThemeDisplay component, we use the useContext hook to access the current value of ThemeContext.

* By simply calling useContext(ThemeContext), we retrieve the current theme value, making it available for rendering.

4 . useReducer: Managing Complex State Transitions

The useReducer hook is like a backup option for useState, especially when handling tricky state situations. You feed it a reducer function and a starting state, and it gives you back the current state plus a function to send actions. The reducer function is in charge of deciding how the state changes when actions are sent.

Example

import React, { useReducer } from 'react';
const initialState = { count: 0 };
const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
};
const Counter = () => {
  // Use useReducer to manage state transitions based on dispatched actions
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
};

* We define an initialState object with a count property set to 0.

* The reducer function defines the logic for updating the state depending on various action types.

* Within the Counter component, we employ the useReducer hook to handle state changes, utilizing both the reducer function and an initialState.

* The state variable stores the present state, while the dispatch function permits us to dispatch actions for state modification.

* In the example, we increment and decrement the count state by dispatching the corresponding action objects.

The way developers construct React applications has been revolutionized by React Hooks. In this blog, we explored the most common hooks: useState, useEffect, useContext, and useReducer. We learned how useState simplifies state management, useEffect handles side effects, useContext simplifies context usage, and useReducer manages complex state transitions. By leveraging these hooks effectively, you can write cleaner, more concise, and maintainable code. Embrace React Hooks to enhance your development workflow and unlock the full potential of React.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 


whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

London

Cybrosys Limited
Alpha House,
100 Borough High Street, London,
SE1 1LB, United Kingdom

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message