DEV Community

Neelakandan R
Neelakandan R

Posted on

1 1 1 1 1

React js-Axios,usestate,useeffect

What is Axios?

Axios is a promise-based HTTP client for JavaScript that simplifies making HTTP requests from both the browser and Node.js environments. It supports all modern browsers and works well in React applications for interacting with APIs and handling HTTP requests.

Key Features of Axios

Promise-based API.

Works in both NodeJS and browsers.

Automatically transforms JSON data.

Supports request and response interceptors.

Allows easy handling of timeouts and cancellation of requests.

supports making GET, POST, PUT, DELETE, and other HTTP requests.

Setting Up Axios in a React Application

Before we start making HTTP requests with Axios, you need to install it. If you’re starting a new React project, create one first using create-react-app (if you haven’t already).

Step 1: Install Axios

To install Axios, run the following command in your React project’s root directory:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Step 2: Import Axios into Your Component

In your React component, import Axios at the top

import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode

Step 3: Add Axios as Dependency

Install Axios library using the command given below

npm i axios

Enter fullscreen mode Exit fullscreen mode

Example:

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    console.log('Data received:', response.data);
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });

Enter fullscreen mode Exit fullscreen mode

useState

state could only be used in class components. But now, with hooks like useState, you can use state in functional components too.

const [state, setState] = useState(initialState)
Enter fullscreen mode Exit fullscreen mode

state: It is the value of the current state.

setState: It is the function that is used to update the state.

initialState: It is the initial value of the state.

How Does useState() Work?

The useState() hook allows you to add state to functional components in React. It works by:

  1. Initialize State: When you call useState(initialValue), it creates a state variable and an updater function.

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

  1. State is Preserved Across Renders: React remembers the state value between re-renders of the component. Each time the component renders, React keeps the latest value of count.

  2. State Updates with the Updater Function: When you call setCount(newValue) React updates the state and it re-renders the component to reflect the new state value.

setCount(count + 1)}>Increment

  1. Triggers Re-render: React will re-render only the component where useState was used—ensuring your UI updates automatically when the state changes.

Why useState is Helpful:

You can easily track changes in your component.

No need for complex code like in class components.

Counter using useState

A common example of using useState is managing the state of a counter with actions to increment and decrement the value.

import { useState } from 'react';
export default function Counter() {
    const [count, setCount] = useState(0);

    function handleClick() {
        setCount(count + 1);
    }
    return (
        <button onClick={handleClick}>
            Click {count} me
        </button>
    );
}
Enter fullscreen mode Exit fullscreen mode

What is useEffect?

useEffect is a React hook that lets you handle side effects in functional components. Side effects are things like:

Fetching data from an API

Setting up a timer

Updating the DOM directly

Subscribing to events

Why Use useEffect?

In class components, side effects like data fetching were handled in lifecycle methods like componentDidMount and componentDidUpdate.

import React, { useEffect } from 'react';

const SimpleEffect = () => {
  useEffect(() => {
    // This runs once when the component is loaded
    console.log("Component has loaded!");

  }, []); // Empty array means it runs only once, when the component mounts

  return <h1>Hello, world!</h1>;
};

export default SimpleEffect;


Enter fullscreen mode Exit fullscreen mode

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay