DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on Edited on

Learning React.js: Components, Hooks, Props, Context API and More

What is React?

React is a JavaScript library used to build user interfaces, especially single-page applications (SPAs).

Some important features of React:

  • Component-based architecture
  • Reusable UI components
  • Virtual DOM
  • State management
  • One-way data flow
  • Hooks for managing component logic

Creating a React Application Using Vite

Vite is a frontend build tool that helps us create and run React applications quickly.

To create a React project, open the terminal and execute:

npm create vite@latest
Enter fullscreen mode Exit fullscreen mode

Follow these steps:

  1. Confirm the installation.
  2. Enter the project name: counter-app
  3. Select the framework: React
  4. Select the variant: JavaScript
  5. Select the linter: ESLint (if prompted)
  6. Navigate to the project folder.
  7. Install dependencies and start the application.
cd counter-app
npm install
npm run dev

Enter fullscreen mode Exit fullscreen mode

Now the React development server will start, and you can open the local URL displayed in the terminal.

Components in React

A component is a reusable piece of UI in React.

We can create components using JavaScript functions. These are called functional components.

Example:

function About() {
    return (
        <h1>Welcome to About Page</h1>
    );
}

export default About;
Enter fullscreen mode Exit fullscreen mode

To use this component in another file:

import About from './About';

function App() {
    return (
        <div>
            <About />
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Here, About is imported and used as a component inside App.

useState Hook

useState is a React Hook used to manage state in functional components.

When the state changes, React re-renders the component to display the updated value.

Example: Counter App

import { useState } from "react";

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

    function increment() {
        setCount(count + 1);
    }

    function decrement() {
        setCount(count - 1);
    }

    function reset() {
        setCount(0);
    }

    return (
        <div>
            <h1>Count: {count}</h1>

            <button onClick={increment}>+</button>
            <button onClick={decrement}>-</button>
            <button onClick={reset}>Reset</button>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Understanding useState:

  • count – Current state value.
  • setCount – Function used to update the state.
  • useState(0) – Sets the initial value to 0.

One important thing I learned: In React, we should update state using its setter function instead of directly modifying the state variable.

useEffect Hook

useEffect is a React Hook used to perform side effects in functional components.

Examples of side effects include:

  • Fetching data from an API.
  • Setting timers and intervals.
  • Adding event listeners.
  • Updating document-related information.

Syntax:

useEffect(() => {
    // Side effect logic
}, []);
Enter fullscreen mode Exit fullscreen mode

Dependency Array in useEffect

The dependency array determines when the effect runs.

  1. Empty dependency array []
useEffect(() => {
    console.log("Component mounted");
}, []);

Enter fullscreen mode Exit fullscreen mode

Runs after the component mounts. In development with React Strict Mode, React may run an additional setup and cleanup cycle.

2. Dependency array with variables

useEffect(() => {
    console.log("Count updated");
}, [count]);
Enter fullscreen mode Exit fullscreen mode

Runs after the initial mount and whenever count changes.

3. Without dependency array

useEffect(() => {
    console.log("Component rendered");
});
Enter fullscreen mode Exit fullscreen mode

Runs after every render.

Component Lifecycle

Every React component has a lifecycle.

The three commonly discussed lifecycle phases are:

  1. Mounting – Component is created and added to the DOM.
  2. Updating – Component re-renders when its props or state change.
  3. Unmounting – Component is removed from the DOM.

With functional components, we commonly manage lifecycle-related behavior using useEffect.

Cleanup Function – Unmounting Example

Let's create a component called Home.jsx.

import { useEffect } from "react";
function Home() {
    useEffect(()=>{
        console.log("Component Mounted");

        const interval= setInterval(() => {
            console.log("hello");


        }, 1000);

        //cleanup function
        return(()=>{
            console.log("component unmounted");
            clearInterval(interval);


        })


    },[])
    return(
        <div>
            Home
        </div>
    )

}
export default Home;
Enter fullscreen mode Exit fullscreen mode

What happens here?

  • When the component mounts, the effect runs.
  • setInterval() prints Hello every second.
  • When the component unmounts, the cleanup function executes.
  • clearInterval() stops the timer.

Cleanup functions are important because they help prevent unnecessary background operations and memory leaks.

Props in React

Props stands for properties.

Props are used to pass data from a parent component to a child component.

Example:

Parent.jsx

function Parent() {
    return (
        <div>
            <Child amount={1000} name="abcd" />
        </div>
    );
}

function Child({ amount, name }) {
    return (
        <div>
            <h2>Amount: {amount}</h2>
            <h2>Name: {name}</h2>
        </div>
    );
}

export default Parent;
Enter fullscreen mode Exit fullscreen mode

Here, amount and name are passed from the parent component to the child component.

Props are read-only. A child component should not directly modify the props it receives.

Props Drilling

Props drilling happens when we pass data through multiple components just to reach a deeply nested child component.

For example:

GrandParent → Parent → Child

The GrandParent passes data to Parent, and Parent passes the same data to Child.

When an application has many nested components, this can make the code difficult to maintain.

Solution: Context API

React Context API helps us share data between components without passing props manually through every intermediate component.

There are three basic steps:

  1. Create a context.
  2. Provide the context value.
  3. Consume the context value.

Example:

GrandParent.jsx

import React from 'react'

export const amountContext = createContext();
const [amount,setAmount] = useState(0);


function Grandparent() {
  return (
    <amountContext.Provider value={amount}>
    <div>
      Grandparent

    </div>
    <amountContext.Provider/>
  )
}

export default Grandparent;
Enter fullscreen mode Exit fullscreen mode

Parent.jsx

import React from 'react'

function Parent() {
  const amount =useContext(amountContext);
  return (
    <div>Parent</div>
  )
}

export default Parent
Enter fullscreen mode Exit fullscreen mode

Here, the Parent component can directly access the amount using useContext() without receiving it through props.

React Router

React Router is a library used to handle navigation between different pages or views in a React application.

First, install React Router DOM:

npm install react-router-dom

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Product from "./Product";
import Cart from "./Cart";

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Product />} />
                <Route path="/cart" element={<Cart />} />
            </Routes>
        </BrowserRouter>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Here:

  • BrowserRouter – Enables browser-based routing.
  • Routes – Groups route definitions.
  • Route – Defines the URL path and corresponding component.

Link Component

We can use Link to navigate between pages without a full browser reload.

import { Link } from "react-router-dom";

function Product() {
    return (
        <div>
            <h1>Product Page</h1>
            <Link to="/cart">View Cart</Link>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

useNavigate Hook

We can also navigate programmatically using useNavigate().

import { useNavigate } from "react-router-dom";

function Product() {

    const navigate = useNavigate();

    function viewCart() {
        navigate("/cart");
    }

    return (
        <button onClick={viewCart}>
            View Cart
        </button>
    );
}

export default Product;
Enter fullscreen mode Exit fullscreen mode

Both Link and useNavigate help us navigate without refreshing the entire page.

useRef Hook

useRef is a built-in React Hook that returns a mutable object with a current property.

The value stored in a ref persists across component re-renders, and updating it does not trigger a re-render.

There are two common uses:

  1. Accessing DOM elements.
  2. Storing values that need to persist between renders without causing a re-render. 3.The useRef Hook can also be used to keep track of previous state values.

Updating a Ref Value

const count = useRef(0);

count.current = count.current + 1;
Enter fullscreen mode Exit fullscreen mode

Here, count.current can be updated without triggering a component re-render.

Diffing Algorithm in React

The Diffing Algorithm is part of React's reconciliation process.

When a component's state or props change, React creates a new representation of the UI and compares it with the previous one.

It identifies the changes and updates the necessary parts of the actual DOM.

useCallback

useCallback is a built-in React Hook that caches a function definition between re-renders. In JavaScript, functions are recreated every time a component renders, so useCallback preserves the exact same function reference unless its specified dependencies change.

import { useCallback, useRef, useState } from "react";

function UseCallbackDemo() {
    const [count, setcount] = useState(0);

    const name = useCallback(() => {
        console.log(name);
    }, []);

    const prevFunction = useRef(name);

    console.log(prevFunction.current);
    console.log(prevFunction.current === name);

    return (
        <div>
            <button onClick={() => setcount(count + 1)}>+</button>
        </div>
    );
}

export default UseCallbackDemo;
Enter fullscreen mode Exit fullscreen mode

What happens with useCallback?

const name = useCallback(() => {
    console.log("Hello");
}, []);
Enter fullscreen mode Exit fullscreen mode
output:
Initial render: true
First click: true
Second click: true
Third click: true
Fourth click: true
Enter fullscreen mode Exit fullscreen mode

When you click the + button:

  1. Count changes.
  2. Component renders again.
  3. React checks the dependencies of useCallback.
  4. Dependencies are [], so they haven't changed.
  5. React reuses the previous function reference.

What happens without useCallback?

const name = () => {
    console.log("Hello");
};

const prevFunction = useRef(name);

console.log(prevFunction.current === name);
Enter fullscreen mode Exit fullscreen mode

Every time the component renders:

  • A new name function is created.
  • prevFunction.current still stores the old function.
  • Both function references are different.
output:
Initial render: true
First click: false
Second click: false
Third click: false
Enter fullscreen mode Exit fullscreen mode

useMemo

  • The React useMemo Hook returns a memoized value.
  • The useMemo Hook only runs when one of its dependencies update.
import { useState, useMemo } from "react";

function UseMemoDemo() {
    const [count, setCount] = useState(0);
    const [number, setNumber] = useState(5);

    const result = useMemo(() => {
        console.log("Calculating...");
        return number * 2;
    }, [number]);

    return (
        <div>
            <h2>Count: {count}</h2>
            <h2>Number: {number}</h2>
            <h2>Result: {result}</h2>

            <button onClick={() => setCount(count + 1)}>
                Increase Count
            </button>

            <button onClick={() => setNumber(number + 1)}>
                Increase Number
            </button>
        </div>
    );
}

export default UseMemoDemo;
Enter fullscreen mode Exit fullscreen mode

When should we use useMemo?

Answer: When we have an expensive calculation and want to avoid recalculating it unnecessarily when unrelated state changes.

useReducer Hook

useReducer is a built-in React Hook used for managing state logic, especially when state updates involve multiple actions or more complex logic.

It works with a reducer function and an initial state.

Syntax:

const [state, dispatch] = useReducer(reducer, initialState);

Example:

import { useReducer } from "react";

function reducer(state, action) {

    switch (action.type) {

        case "increment":
            return { count: state.count + 1 };

        case "decrement":
            return { count: state.count - 1 };

        case "reset":
            return { count: 0 };

        default:
            return state;
    }
}

function App() {

    const [state, dispatch] = useReducer(reducer, { count: 0 });

    return (
        <div>
            <h1>Count: {state.count}</h1>

            <button onClick={() => dispatch({ type: "increment" })}>
                +
            </button>

            <button onClick={() => dispatch({ type: "decrement" })}>
                -
            </button>

            <button onClick={() => dispatch({ type: "reset" })}>
                Reset
            </button>
        </div>
    );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

Understanding the terms:

  • reducer – Function that decides how the state should change.
  • state – Current state value.
  • dispatch – Function used to send an action.
  • action – Describes what change should happen.

Tailwind CSS

Tailwind CSS is a utility-first CSS framework.

Instead of writing separate CSS classes for every style, we can apply utility classes directly in HTML or JSX.

Example:

function App() {
    return (
        <div className="bg-blue-500 text-white p-5 rounded-lg">
            <h1 className="text-2xl font-bold">
                Welcome to React
            </h1>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Installing Tailwind CSS with Vite

The installation steps depend on the Tailwind version.
For Tailwind CSS v4, the Vite integration generally uses:

npm install tailwindcss @tailwindcss/vite

Configure the Tailwind Vite plugin in vite.config.js:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";

export default defineConfig({
    plugins: [react(), tailwindcss()],
});
Enter fullscreen mode Exit fullscreen mode

Then add this to your CSS file:

@import "tailwindcss";
Enter fullscreen mode Exit fullscreen mode

Now you can use Tailwind utility classes in your React components.

References

Top comments (0)