Getting Started with React!

Getting Started with React!

Note: This is a quick guide to build a react project from scratch. detailed theory is avoided, only focused on implementation part.

for detailed information read official documentation: https://react.dev/learn

Creating react project

1. Setup

  • Open the terminal in the desired folder where you want to store your project.

  • Run the following command to create a new React project using Vite:

      npm create vite@latest
    

2. Project Initialization

  • Enter a name for your project when prompted.

  • Choose the framework: Select React.

  • Select the variant: Choose JavaScript.

    This will initialize a new React project with Vite.

3. Navigate to Your Project

  • Move into your new project directory:

      cd 01_reactbasics
    

4. Install Dependencies

  • Run the following command to install the required packages:

      npm install
    

5. Run the Development Server

  • Start the development server to preview your app:

      npm run dev
    

    Your project should now be running locally!

6. Clean Up Unnecessary Files

  • Delete the following files to streamline the project:

    • assets folder

    • App.css

    • index.css

  • Clean the following files:

    • App.jsx: Remove default boilerplate code.

    • main.jsx: Keep it minimal by removing extra comments or unnecessary imports.

React Structure

In our project we have three important files, index.html, main.jsx, App.jsx

index.html:

This is a regular HTML file that serves as the main page of the website. It contains a div with the id="root" where your React app will be rendered.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Title of website</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

main.jsx:

This file is responsible for rendering the main component (App.jsx) inside the root div of index.html.

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'


createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)
  • createRoot: Creates a root where your React app will be rendered inside the root div.

  • <StrictMode>: Helps identify potential problems in an application by wrapping the <App /> component.

  • <App />: This tag refers to the App component defined in App.jsx.

App.jsx:

The App component is the heart of your React app, written as a JavaScript function that returns HTML-like code (JSX).

JSX: This is a special syntax that lets you write HTML-like elements directly in your JavaScript code.

function App() {
  return (
    <>
       Hello world
    </>
  )
}

export default App

React Components

Rules for Components in Vite + React:

  1. File Extension: Components should be saved with the .jsx extension.

  2. Component Naming: Component names must start with an uppercase letter. This is required for React to distinguish between built-in HTML tags and custom components.

  3. Returning a Single Element: A React component must return only one component. To include multiple elements, wrap them inside React fragments (<>...</>).

Component.jsx

function Component() {
  return (
    <>
       <h1> Welcome to React Series <h1/>
       <p> Quick guide to build project <p/>
    </>
  )
}

export default Component

App.js

import Component from 'Component.jsx'

function App() {
  return (
    <>
       <Component /> 
    </>
  )
}

export default App

React Hooks

What are Hooks?

Hooks allow you to use state and other React features in functional components.

Why we need hooks?

  • Enable state in functional components.

  • Simplify reusable logic.

  • Make code cleaner and easier to maintain.

useState() Hook

Add state to functional components.

Syntax:

const [state, setState] = useState(initialValue)
  • state: Current state value.

  • setState: Function to update the state.

Example:

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

Why Do We Need useState hook?

  • State in Functional Components: useState allows functional components to store and manage state, which was previously only possible in class components.

  • Dynamic Data: Helps handle dynamic data like form inputs, button clicks, and any value that changes over time.

  • Rerender on State Change: When the state updates via setState, React automatically re-renders the component with the new state value.

Callbacks in setState

import React, { useState } from 'react';

function Counter() {
  const [counter, setCounter] = useState(0);

  const handleClick = () => {
    setCounter(counter + 1);
    setCounter(counter + 1);
    setCounter(counter + 1);
    setCounter(counter + 1);
    // What do you think the final value of counter will be after clicking the button?
  };

  return (
    <div>
      <p>Counter: {counter}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

export default Counter;

After clicking the button, the final value of counter will be 1.

Why Does setCounter Reflect Only Once?

React batches multiple state updates into a single update to prevent unnecessary re-renders. When you call setCounter multiple times in a synchronous block, React waits to apply all the updates at once before re-rendering the component. Therefore, only the last update is reflected.

Solution?

To fix this, React provides a way to update the state based on the previous state using a callback function inside the setCounter call. This ensures that each update uses the most recent state value, avoiding stale state issues.

 const handleClick = () => {
    setCounter((prevCounter) => prevCounter + 1);
    setCounter((prevCounter) => prevCounter + 1);
    setCounter((prevCounter) => prevCounter + 1);
    setCounter((prevCounter) => prevCounter + 1);
    // Counter will increase by 4
  };