Every React Concept Explained in 5 Minutes
Jitendra Choudhary

Jitendra Choudhary @jitendrachoudhary

About: Full Stack Developer | Open Source | Technical Writer | Flame University

Location:
India
Joined:
Jan 30, 2024

Every React Concept Explained in 5 Minutes

Publish Date: Jul 29 '24
798 62

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>Join us, {props.name}!</h1>;
}


Enter fullscreen mode Exit fullscreen mode

Note:

  • Functional Components are recommended instead of Class based.
  • Functional components are often called statefull components when the UI is updated dynamically due to state's value not Prop's value.
  • Functional components are called stateless components when it uses Prop's value to dynamically change UI not state's value.

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 className="head">This is H1!</h1>


Enter fullscreen mode Exit fullscreen mode

Now, TSX is a file extension for TypeScript files that contains JSX syntax. With TSX you can write type-checked code with the existing JSX syntax. TypeScript is not a different language, it is just a superset of JavaScript that adds optional static typing.

More simply, with TSX files you can write React components using TypeScript and JSX together.

Example of TSX



interface AgeProps {
  age: number;
}

const GreetAge = (props: AgeProps) => {
  return (
    <div>
      Hello, you are {props.age} old.
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

Note:

  • JSX files uses a `.jsx` file extension.
  • TSX files uses a `.tsx` file extension.
  • TypeScript's type system helps catch potential errors early in development.

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>Eat</h1>
      <button>Learn more</button>
      <p>Code is Fun</p>
      <button>Repeat</button>
    </>
  );
}


Enter fullscreen mode Exit fullscreen mode

Note:

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

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>;
}


Enter fullscreen mode Exit fullscreen mode

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)


Enter fullscreen mode Exit fullscreen mode

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 />
        <Sidebar />
        <Content />
        <Footer />
     </StrictMode>
    </>
  )
}


Enter fullscreen mode Exit fullscreen mode


Strict Mode in React Showing Browser Console

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>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>
      </>
  );
}


Enter fullscreen mode Exit fullscreen mode

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 createContext() 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>{`Current Count: ${count}!`}</h1>
      <Button />
    </UserContext.Provider>
  );
}


Enter fullscreen mode Exit fullscreen mode

Use useContext hook to access the value of age.



import { useContext } from "react";

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

  return (
    <>
      <h1>This is GrandChildConsumer</h1>
      <h2>{`Current Count: ${count}`}</h2>
    </>
  );
}


Enter fullscreen mode Exit fullscreen mode
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 (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}> {fruit} </li>
      ))}
    </ul>
  );
}




Enter fullscreen mode Exit fullscreen mode
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>
  );
}


Enter fullscreen mode Exit fullscreen mode

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>
  );
}


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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 path="about" element={<About />} />
          <Route path="contact" element={<Contact />} />
          <Route path="*" element={<NoPage />} />
      </Routes>
    </BrowserRouter>
  );
}


Enter fullscreen mode Exit fullscreen mode

First wrap your content into the <BrowserRouter>. Then we define <Routes> and inside that introduces the <Route> for navigation. <Route> 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 < Routes >.
  • < Route > can be nested.
  • `react-router-dom` also has < Link > and < Outlet > 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.

Comments 62 total

  • Afaz Khatri
    Afaz KhatriJul 30, 2024

    Great article.

    I find the content on the useContext example to be inaccurate. Can you please update it?

    • Jitendra Choudhary
      Jitendra ChoudharyJul 30, 2024

      Thanks for pointing out the inaccuracy in the useContext example.

      I have updated the explanation and corrected the errors in the code snippet.

  • Peter Galiba
    Peter GalibaJul 30, 2024

    Fragments can have keys.

    • Jitendra Choudhary
      Jitendra ChoudharyJul 30, 2024

      Your are absolutely right,

      I appreciate you bringing this up.

  • Hasan Farook
    Hasan FarookJul 30, 2024

    This is awesome. Thanks

  • Shravan G.T
    Shravan G.TJul 30, 2024

    Next do for angular pls

  • WTP | WhatThePortal.com
    WTP | WhatThePortal.comJul 30, 2024

    Do add TSX as the primary variant to JSX - don't want new folks going down that path unnecessarily!

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      Thanks for the suggestion; it improves the content of the article.

      I have updated the article.

  • Muhammad Irshad
    Muhammad IrshadJul 30, 2024

    Thunk you am new hear please guide me how to Best liptop use for apple MacBook pro for web development and web design also use for software Engineer please guide me

  • Matthew
    MatthewJul 30, 2024

    A bit more than 5 min but a good read regardless.

    Thank you for sharing.

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      I'm glad you found the article worth the read, even though it took a bit more than 5 minutes.

      LOL!! It's a 5-minute article but due to the intro, conclusion, and code snippet, it took longer.

  • Sadaqat Ali
    Sadaqat AliJul 30, 2024

    Good information

  • Steven Olsen
    Steven OlsenJul 30, 2024

    Review the notes for hooks, they aren't accurate.

    Thanks for the article!

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      Thanks, Steven, for your feedback. Can you be more specific about the inaccuracy?

      I would love to correct any errors and update the article accordingly.

  • nikhilprajapati1080@gmail.com
    nikhilprajapati1080@gmail.comJul 30, 2024

    React portal?

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      Yes, I missed out on Virtual DOM, Portal, and a few more concepts.

  • Andrey Sharypov
    Andrey SharypovJul 30, 2024

    Is there some feeling of the GPT generation? 😁

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      You decide and let me know.😇 For real

      • velu-murugesan
        velu-murugesanAug 2, 2024

        I have some knowledge in react and node how can I get a entry level job as a fresher

        • Jitendra Choudhary
          Jitendra ChoudharyAug 2, 2024

          Let's be honest, it's impossible to guarantee a job.

          To maximize the chances of getting a job, you can:

          Gain practical experience by building projects; you can checkout @bigsondev blog on webdev.

          Try Open Source

          Intern at a local tech company.

          Reach out to potential employers.

          Engage in extensive networking to connect with as many people as possible for job opportunities.

  • Chandan
    ChandanJul 30, 2024

    Nicely Explained 👏🏻👍🏻

  • Vilmos Bartalis
    Vilmos BartalisJul 30, 2024

    Thanks for the intro. That was easy to digest from the pov of a angular/astro dev.

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      I'm happy to hear you found it easy to understand. Thank you for bringing a smile to my face.

  • Syed Shoebuddin
    Syed ShoebuddinJul 31, 2024

    great article

  • Justin3go
    Justin3goJul 31, 2024

    Thank you, for someone like me who doesn't use React often, I reviewed a lot of knowledge

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      Thank you for your love. I hope I am fulfilling my goal of technical writing.

  • Zigah Christian
    Zigah ChristianJul 31, 2024

    This is simple and awesome, Big thanks for the Effort.

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      Big thanks for taking the time to read it and for the kind words

  • chovy
    chovyJul 31, 2024

    This is awesome. I wish you'd write one for react native.

    • Jitendra Choudhary
      Jitendra ChoudharyJul 31, 2024

      Thanks you so much!!

      A React Native article sounds like a great idea-- l''ll definitely try my best to write.

  • Rowland
    RowlandAug 1, 2024

    Very nice and succinct. It captures the fundamental concepts in using react. One thing I'll suggest is the implementation of react router v6

    • Jitendra Choudhary
      Jitendra ChoudharyAug 2, 2024

      Hi Rowland, I'm glad you found the article helpful.

      I didn't include the React Router v6 features because I felt it would be beyond the scope of the article. However, I did mention , which enables client-side rendering. I'll do my best to include react-router v6

  • Leonardo Beron
    Leonardo BeronAug 2, 2024

    Thanks guy.

  • Joao Polo
    Joao PoloAug 2, 2024

    Awesome. Clear. Fast. Congrats!

  • Chukwunonso Orjiakor
    Chukwunonso OrjiakorAug 4, 2024

    Interesting article for beginners. Well done Jitendra.

    Quick note: A Functional component is only referred to as stateless, if it is not managing any state value, and is relying on Props value for it's dynamic data.

    • Jitendra Choudhary
      Jitendra ChoudharyAug 5, 2024

      Thanks for your correction & kind words.

      I have updated the post.

  • Kundan Kumar
    Kundan KumarAug 10, 2024

    Nice

  • harry li
    harry liAug 26, 2024

    it‘s useful but it's not very deep

    • Jitendra Choudhary
      Jitendra ChoudharyAug 26, 2024

      I think that's the most one can get out of 5 minutes.

      I'm glad you found this helpful!!

  • Sushant Jarial
    Sushant JarialSep 9, 2024

    Isn't state should be defined in lowest common ancestor instead of top level component. If we define state at top level component then when the state changes every component rerenders. But we define it lowest component then only where the component where the state is used get rerenders.

    • Jitendra Choudhary
      Jitendra ChoudharySep 12, 2024

      Naah, Passing data is one way in React (from high to low level). In order to avoid unnecessary renders, React has Redux, Zustand. This state management libs directly passes the state to the required component hence improving performance.

      Also, there a thing "lifting up the state", we lift the state to common ancestor so that it can be passed to its child easily.

  • RoyLizhiyu
    RoyLizhiyuSep 11, 2024

    nice recap

  • Omozemoje Augustine Oisasoje
    Omozemoje Augustine OisasojeSep 12, 2024

    This is an in depth Technical blog

  • Alioune Touré
    Alioune TouréOct 15, 2024

    Thank you for your article.
    I started learning react recently and you helped me understand some things better.

  • obuhdaniel
    obuhdanielOct 21, 2024

    Your Explanation of Context API is simple and understandable

  • Anand259
    Anand259Oct 28, 2024

    I appreciate your post. Please also explain hooks in detail like useState, useEffect, useRef, useCallback, etc.

  • Babalola Elisha
    Babalola ElishaJan 3, 2025

    Thank you

  • Mateus Cazuza
    Mateus CazuzaJan 7, 2025

    Awesome article, congratulations @jitendrachoudhary

    On item 11, I would recommend using the index as a key when the list is not dynamic because React uses the key to reference its components.

Add comment