Terms and Functionality in React.js
Agbo, Daniel Onuoha
Posted on November 16, 2024
React.js, commonly referred to as React, is a powerful JavaScript library used for building user interfaces, particularly for single-page applications (SPAs). It enables developers to create complex UIs by breaking them down into smaller, reusable components. To fully harness the power of React, it’s important to understand its core terms and functionalities. In this article, we'll break down some of the key concepts, terms, and functionality that you need to know when working with React.js.
1. Components
Function Components:
Function components are the most common way to define React components today. They are simply JavaScript functions that return JSX (JavaScript XML) representing the UI. Function components can also use React Hooks to manage state and side effects.
function Greeting() {
return <h1>Hello, World!</h1>;
}
Class Components:
Before the introduction of React Hooks, class components were the primary way to manage component state and lifecycle methods. Although they are still widely used, function components with hooks are now the preferred method.
class Greeting extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
2. JSX (JavaScript XML)
JSX is a syntax extension for JavaScript that allows you to write HTML-like code directly within JavaScript. React uses JSX to describe what the UI should look like. Even though it looks like HTML, JSX is compiled into JavaScript under the hood.
const element = <h1>Hello, JSX!</h1>;
You can also embed JavaScript expressions inside JSX by wrapping them in curly braces:
const name = "React";
const element = <h1>Hello, {name}!</h1>;
3. State
State is a built-in React object that is used to store information about a component’s current situation. Each component can manage its own state and re-render when that state changes. Function components use the useState
hook to manage state, while class components use the this.state
object.
Example with useState
(Function Component):
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Example with this.state
(Class Component):
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
4. Props (Properties)
Props are used to pass data from one component to another. They are like function arguments that allow components to communicate with each other. Props are read-only and cannot be modified by the receiving component.
Example:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return <Welcome name="React" />;
}
In this example, the Welcome
component receives the name
prop from the App
component and renders "Hello, React".
5. Hooks
Hooks are functions that allow you to "hook into" React state and lifecycle features in function components. The two most commonly used hooks are:
useState
:
Allows you to add state to function components.
const [state, setState] = useState(initialState);
useEffect
:
Handles side effects like data fetching, subscriptions, or manually changing the DOM after every render.
useEffect(() => {
// Code to run after every render or when specific state/props change
}, [dependency]); // Dependency array
Other commonly used hooks include useContext
, useReducer
, useRef
, and useCallback
.
6. Virtual DOM
React uses a Virtual DOM, a lightweight copy of the actual DOM, to optimize UI updates. Instead of directly manipulating the real DOM, React first updates the virtual DOM and then figures out the minimal changes required to bring the actual DOM in sync with the virtual version. This process is called reconciliation and significantly improves performance, especially in large applications.
7. Lifecycle Methods (Class Components)
Lifecycle methods are special methods in class components that allow you to hook into different stages of a component's life (rendering, updating, and unmounting). Some important lifecycle methods include:
componentDidMount()
: Invoked once after the component has been mounted to the DOM. Used for initial data fetching or subscriptions.componentDidUpdate()
: Called after every re-render. Used to perform updates based on state or prop changes.componentWillUnmount()
: Invoked just before a component is removed from the DOM. Used for cleanup tasks like cancelling API calls or removing event listeners.
In function components, you can achieve the same functionality using useEffect
.
8. Conditional Rendering
In React, you can conditionally render components or elements based on state or props. The most common method is using JavaScript's ternary operator.
Example:
function Greeting(props) {
return props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>;
}
Other approaches to conditional rendering include using if
statements or short-circuiting (&&
) in JSX.
9. Lists and Keys
In React, lists of elements are created using the .map()
method. Each item in a list should have a unique "key" prop to help React optimize rendering.
Example:
const items = ['Apple', 'Banana', 'Cherry'];
const itemList = items.map((item, index) => <li key={index}>{item}</li>);
Keys should be unique and stable, helping React identify which items have changed, been added, or removed.
10. Forms and Controlled Components
In React, forms are typically handled using controlled components, where form elements (like inputs) are controlled by React state. This allows React to fully control the value of form elements.
Example:
function Form() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
return (
<form>
<input type="text" value={name} onChange={handleChange} />
</form>
);
}
In this example, the input’s value is controlled by the React state, ensuring that any change in the input field is captured in real time.
11. Context API
The Context API allows you to share state or data between components without having to pass props down manually at every level (also known as "prop drilling"). It’s particularly useful when you need to pass global data (like user authentication or theme settings) throughout your app.
Example:
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemeButton />;
}
function ThemeButton() {
const theme = useContext(ThemeContext);
return <button>{theme}</button>;
}
Conclusion
React.js offers a wide range of features and terms to master. From the fundamentals of components, JSX, state, and props to more advanced concepts like hooks, context, and lifecycle methods, React provides a flexible and scalable framework for building modern web applications. Understanding these key concepts and terms will allow you to unlock the full potential of React and build robust, maintainable, and dynamic user interfaces.
Posted on November 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.