React JS Fundamentals: An Introduction
React JS, often simply called React, is a JavaScript library for building user interfaces (UIs). Developed and maintained by Facebook (now Meta) and a community of individual developers and companies, React has become the dominant force in front-end development. This article provides a comprehensive introduction to the core concepts of React, laying the groundwork for building interactive and dynamic web applications.
1. Why React?
React offers several compelling advantages over traditional “vanilla” JavaScript or other libraries for UI development:
-
Component-Based Architecture: React’s core philosophy revolves around breaking down the UI into small, reusable, and independent pieces called components. This modular approach makes code more manageable, organized, testable, and scalable. Think of components like Lego bricks – you build individual pieces (like a wheel or a window) and then assemble them to create a complete car (your application).
-
Declarative Programming: React emphasizes what should be rendered, not how. You describe the desired UI state, and React takes care of updating the DOM (Document Object Model – the browser’s representation of your webpage) efficiently. This contrasts with imperative programming, where you explicitly manipulate the DOM element by element.
-
Virtual DOM: React uses a virtual DOM, a lightweight in-memory representation of the actual DOM. When changes occur in your application’s data, React updates the virtual DOM first. It then compares the new virtual DOM with the previous version and calculates the minimum number of changes needed to update the actual DOM. This process, called reconciliation, significantly improves performance, especially in complex applications.
-
One-Way Data Binding: Data flows in a single direction in React, from parent components to child components (downwards). This unidirectional data flow makes it easier to track changes, debug issues, and reason about the application’s state. Child components cannot directly modify the data they receive from their parents.
-
JSX (JavaScript XML): React uses JSX, a syntax extension to JavaScript that looks similar to HTML. JSX allows you to write HTML-like structures directly within your JavaScript code, making it more intuitive and readable to define UI elements. While it looks like HTML, JSX gets compiled into regular JavaScript function calls.
-
Large and Active Community: React boasts a massive and vibrant community, providing ample resources, libraries, tutorials, and support. This active ecosystem ensures continuous development, improvements, and readily available solutions to common problems.
-
Learn Once, Write Anywhere: The knowledge you gain with React can be applied to a variety of platforms. With libraries like React Native, you can build native mobile applications for iOS and Android using the same core concepts.
2. Key Concepts:
Let’s dive into the fundamental building blocks of React:
a) Components:
Components are the heart of React. They are independent, reusable pieces of UI. There are two primary types of components:
-
Functional Components: These are JavaScript functions that accept
props
(properties – data passed from parent components) as input and return JSX, which describes the UI to be rendered. Functional components are increasingly favored due to their simplicity and the introduction of Hooks.javascript
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
} -
Class Components: These are ES6 classes that extend the
React.Component
class. They have arender()
method that returns JSX. Class components can manage their own state usingthis.state
.javascript
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
b) JSX (JavaScript XML):
JSX is a syntax extension that allows you to write HTML-like code within your JavaScript. It’s not HTML; it’s a more readable way to describe UI elements in React. JSX expressions must have a single root element.
“`javascript
const element = (
Hello!
This is JSX.
);
“`
Under the hood, the JSX above gets transformed into something like this (using React.createElement
):
javascript
const element = React.createElement(
'div',
null,
React.createElement('h1', null, 'Hello!'),
React.createElement('p', null, 'This is JSX.')
);
c) Props (Properties):
Props are how data is passed from parent components to child components. They are read-only within the child component. Props can be of any JavaScript data type (strings, numbers, arrays, objects, functions, etc.).
“`javascript
// Parent Component
function App() {
return
}
// Child Component (Functional)
function Welcome(props) {
return
Hello, {props.name}!
; // Accessing the ‘name’ prop
}
“`
d) State:
State is data that can change over time within a component. Only class components can have their own state (using this.state
). Functional components can manage state using Hooks (explained below). When state changes, React re-renders the component and its children (if necessary) to reflect the updated data.
“`javascript
// Class Component with State
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 }; // Initializing state
}
handleClick = () => {
this.setState({ count: this.state.count + 1 }); // Updating state
}
render() {
return (
Count: {this.state.count}
);
}
}
“`
e) Hooks (useState, useEffect, and others):
Hooks were introduced in React 16.8 and allow functional components to “hook into” React features like state and lifecycle methods (previously only available in class components).
-
useState
: Provides a way to add state to functional components. It returns a state variable and a function to update it.“`javascript
import React, { useState } from ‘react’;function Counter() {
const [count, setCount] = useState(0); // count is the state, setCount is the updaterreturn (
Count: {count}
);
}
“` -
useEffect
: Allows you to perform side effects in functional components (e.g., fetching data, setting up subscriptions, manually manipulating the DOM). It runs after every render by default, but you can control when it runs using a dependency array.“`javascript
import React, { useState, useEffect } from ‘react’;function Example() {
const [count, setCount] = useState(0);// This effect runs after every render
useEffect(() => {
document.title =You clicked ${count} times
;
});
// To run only once (like componentDidMount), pass an empty array: useEffect(() => { … }, []);
// To run when ‘count’ changes: useEffect(() => { … }, [count]);return (
You clicked {count} times
);
}
“`
There are many other built in hooks, like useContext, useReducer, useCallback, useMemo, etc.
f) Events:
React handles events similarly to how they are handled in the DOM, but with some key differences:
- Event handlers are passed as functions, not strings.
- Event names are camelCased (e.g.,
onClick
instead ofonclick
). - You prevent default behavior using
event.preventDefault()
instead of returningfalse
. - React wraps native browser events into it’s own SyntheticEvent to ensure consistency across browsers.
“`javascript
function MyButton() {
function handleClick(event) {
event.preventDefault(); // Prevent default behavior (e.g., form submission)
console.log(‘Button clicked!’);
}
return (
);
}
“`
g) Conditional Rendering:
You can render different UI elements based on conditions using standard JavaScript operators (like if
, else
, ternary operators, or logical AND (&&
)).
“`javascript
function LoginControl() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
let button;
if (isLoggedIn) {
button = ;
} else {
button = ;
}
return (
Welcome back!
:
Please log in.
}
{button}
);
}
“`
or:
javascript
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
return (
<div>
{isLoggedIn && <h1>Welcome Back!</h1>}
{!isLoggedIn && <h1>Please Sign In</h1>}
</div>
)
}
h) Lists and Keys:
When rendering lists of elements, you should provide a unique key
prop to each item. Keys help React identify which items have changed, been added, or been removed, optimizing the reconciliation process. Keys must be unique amongst siblings. Often you will use the ID of the list item as the key.
“`javascript
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
{number}
);
return (
- {listItems}
);
}
const numbers = [1, 2, 3, 4, 5];
“`
3. Setting Up a React Project:
The easiest way to start a new React project is using create-react-app
, a command-line tool that sets up a basic development environment with all the necessary dependencies.
- Install Node.js and npm (or yarn): Node.js comes with npm (Node Package Manager). Yarn is an alternative package manager.
- Run
create-react-app
:
bash
npx create-react-app my-app
cd my-app
npm start # Or yarn start
This will create a new directorymy-app
with a basic React project structure and start a development server.
4. Conclusion:
This article has provided a foundational understanding of React JS, covering its core principles, key concepts, and how to set up a basic project. By mastering these fundamentals, you’ll be well-equipped to build dynamic and interactive web applications with React. The next steps in your learning journey should involve practicing these concepts by building small projects, exploring the React documentation, and delving into more advanced topics like context, reducers, and routing. Remember that consistent practice is key to becoming proficient in React.