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>;
}
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>
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>
);
};
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>
</>
);
}
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.
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>
</>
)
}
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>
</>
);
}
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>
);
}
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>
</>
);
}
Note: The useContext
hook is often used instead of Consumer for better readability and simplicity.