search
HomeWeb Front-endJS TutorialEvery React Concept Explained in inutes

React is a JavaScript library that allows you to develop front-end code in minutes. It has pre-built methods and functions to perform certain tasks. React as a library includes complex terms like reconciliation, state, props, etc. What do they actually mean?

In this article, you will learn about this exaggerated concept more simply.

1. Components

Components are small bit of reusable code that return a React element to be rendered on a webpage. It is a group of code that make up a single part of the webpage like buttons, navbar, cards, etc. It is just like a JavaScript function but returns a rendered element. It accepts parameters called "Props". Components are named with capital case.

Example Of Functional Component

function Heading(props) {
  return <h1 id="Join-us-props-name">Join us, {props.name}!</h1>;
}

Note:

  • Functional Components are recommended instead of Class based.
  • Functional components are often called stateless components.

2. JSX

JSX is JavaScript XML, which allows us to write HTML in React. It introduces XML-like tags and attributes to create React elements. It makes it easy to create React Components by letting you write HTML-like code in .jsx files. Instead of using complicated JavaScript, JSX makes the code readable and clean. React DOM uses camelCase for attribute naming such as htmlFor, onClick.

Example of JSX

<h1 id="This-is-H">This is H1!</h1>

3. Fragments

Fragments in React allows you to return multiple elements from a component. It groups the list of elements without creating a extra DOM nodes. It cleans all the extra divs from the DOM. This quickly renders the UI.

Example of Fragments

const App = () => {
  return  (
    
      <h1 id="Eat">Eat</h1>
      <button>Learn more</button>
      <p>Code is Fun</p>
      <button>Repeat</button>
    >
  );
}

Note:

  • Fragments makes the code cleaner and readable.
  • It are memory efficient.
  • It cannot have CSS styles and Keys.

4. Props

"Props" is a special keyword in React that stands for properties. It is used to transfer data between components. The follow of data transfer is uni-directional i.e from parent component to child component.

Example of Props

function Head(props) {
  return <p>{props.children}</p>;
}

Note: Props is read-only, which ensures that child components don't manipulate the value coming from parent component.

5. State

Components need to keep track of certain values when user interacts. Let's say the light/dark mode theme toggle button changes its value(from light to dark & vice versa) when a user clicks on the button. Components need to remember the current value of theme. In React, this kind of component-specific memory is called state.

State is defined using a useState() hook; more on that later.

Example of defining state

const [index, setIndex] = useState(0)

Note: It's always a good practice to define state in a top-level component to share it easily with other child components and ensure a single source of truth.

6. Lifecycle Methods

Lifecycle methods are special functions you can use within React classes to perform actions at various stages of a component's existence. These stages are:

  • Mounting: When a component is first created and inserted into the DOM.
  • Updating: When a component's props or state change, causing the component to re-render.
  • Unmounting: When a component is removed from the DOM.

7. Purity

Purity in functional programming is when a given same input returns the same output. The inputs is the only factor that determine the output then the function is said to be pure.

In React a component is said to be pure when it returns the same output for the same input (viz props)

8. Strict Mode

Strict Mode is a developmental feature in react that enables extra safety features to improve code quality. It shows warnings regarding potential errors and bugs into the code. It logs warning into the browser's console.

Example of Strict Mode

import { StrictMode } from 'react';

function App() {
  return (
    
     <strictmode>
        <header></header>
        <sidebar></sidebar>
        <content></content>
        <footer></footer>
     </strictmode>
    >
  )
}


Every React Concept Explained in inutes

Strict Mode in React Showing Browser Console

9. Hooks

Hooks in React allows to use state and other React features without writing class components. Hooks are functions that provide access to React's state management, side effects, and other features.

Some commonly used hooks: useState, useMemo, useRef, etc.

Example of Hooks

import React, { useState } from "react"; // Importing useState hook;

function FavoriteColor() {
  const [color, setColor] = useState("red"); // Initializing the state and setter function;

  return (
    
      <h1 id="My-favorite-color-is-color">My favorite color is {color}!</h1>
      <button type="button" onclick="{()"> setColor("blue")} // Updating the state;
        >Blue</button>
      <button type="button" onclick="{()"> setColor("red")} // Updating the state;
      >Red</button>
      <button type="button" onclick="{()"> setColor("yellow")} // Updating the state;
      >Yellow</button>
      >
  );
}

Note:

  • Hooks can only be called inside React function components.
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional.

10. Context API

The Context API is used to share data like state, functions across the component tree without passing props down manually at every level. It avoids prop drilling by simplifying state management and sharing data across the component. With Context API the data is shared directly with the child component who will consume it.

The useContext() method is used to create a context. This function returns a context object with two components – a Provider and a Consumer.

The Provider is used to wrap the part of your component tree where you want the context to be available. It accepts a compulsory value prop that holds the data you want to share across other components.

The useContext hook is used to access the data.

Example of Context API

Create a context using createContext() method. Wrap child components in the Context Provider and supply the state value.

import { useState, createContext} from "react";

const UserContext = createContext();

function ParentCounter() {
  const [count, setCount] = useState(10);

  return (
    <usercontext.provider value="{count}">
      <h1 id="Current-Count-count">{`Current Count: ${count}!`}</h1>
      <button></button>
    </usercontext.provider>
  );
}

Use useContext hook to access the value of age.

import { useContext } from "react";

function GrandChildConsumer() {
  const age = useContext(UserContext);

  return (
    
      <h1 id="This-is-GrandChildConsumer">This is GrandChildConsumer</h1>
      <h2 id="Current-Count-count">{`Current Count: ${count}`}</h2>
    >
  );
}
Note: The `useContext` hook is often used instead of Consumer for better readability and simplicity.

11. Lists and Keys

A Key is a special kind of attribute for list items in React. It acts as a unique identifier for each items when it is updated, deleted, or added.

Assigning index of the item as the Key is discouraged because if the items are rearranged it will affect the expected behavior.

Imagine in shopping cart you have 10 items added and each item have a unique index as a Key. Now, you decide to remove the first and fifth item from the cart. When the items are removed the indexing will change; the second item will become first and sixth item will become fifth item.

Example of Lists and Keys

const fruits = ["apple", "banana", "orange"];

function FruitList() {
  return (
    
    {fruits.map((fruit, index) => (
  • {fruit}
  • ))}
); } Note:
  • It is recommended to use string as a `Key` that uniquely identifies the item in the list.
  • Third-party libraries like UUID offer the functionality to create unique keys.

12. Form: Controlled & Uncontrolled Components

React forms allows to collect and manage user input better than traditional HTML form. These forms are built using components and store the user inputs into state. There are two types of components:

Controlled Components

In Controlled components, the form's state is managed by the component himself. This is the recommended approach for managing form data in React. When the user interacts with the form (e.g., typing in an input field), the component's state is updated to reflect the changes.

Example of Controlled Component

function ControlledInput() {
  const [name, setName] = useState('');

  const handleChange = (e) => {
    setName(e.target.value);
  }

  return (
    <div>
      <label htmlfor="name">Name: </label>
      <input type="text" id="name" value="{name}" onchange="{handleChange}">
      <p>Your name is: {name}</p>
    </div>
  );
}

Uncontrolled Components

Uncontrolled components rely on the DOM to manage the form data. The component doesn't directly control the form's state, but it can access the values using DOM methods like ref.

Example of Uncontrolled Component

function UncontrolledInput() {
  const nameRef = useRef(null);

  const handleClick = () => {
    console.log(nameRef.current.value);
  }

  return (
    <div>
      <label htmlfor="name">Name: </label>
      <input type="text" id="name" ref="{nameRef}">
      <button onclick="{handleClick}">Get Name</button>
    </div>
  );
}

Note:

  • Controlled components provides form validation because the user's input is instantly reflected due to use of state.
  • Form validation is not possible in uncontrolled components because the user's input can only be accessed after the form is submitted.

13. React Router

  • Introduction to React Router for navigation
  • Basic setup and usage
  • Example: Creating routes and navigating between pages

React Router is a standard library for routing in React. It enables navigation among various components in the React app. It allows changing the browser URL and syncing the UI with the URL. React Router is important for creating single-page applications (SPA) with navigation features.

First, you need to install React Router from your terminal.

Installing React Router

# If you are using npm
npm install react-router-dom

# If you are using yarn
yarn add react-router-dom

Example of React Router

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {
  return (
    <browserrouter>
      <routes>
          <route path="/" element="{<Home"></route>} />
          <route path="about" element="{<About"></route>} />
          <route path="contact" element="{<Contact"></route>} />
          <route path="*" element="{<NoPage"></route>} />
      </routes>
    </browserrouter>
  );
}

First wrap your content into the . Then we define and inside that introduces the for navigation. has path which specifies URL of the page and element attribute which specifies the component that needs to be rendered on the defined path.

Note:

  • An app can have multiple .
  • can be nested.
  • `react-router-dom` also has and Component for navigation.

Conclusion

The best way to learn any programming language is to practice more projects. Build small projects and experiment with the concepts.

If you find this post helpful don't forget to keep showing me love. Until next time like, share, and learn.

You can also stay connected with me by following me here and on X, GitHub, and LinkedIn.

The above is the detailed content of Every React Concept Explained in inutes. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use