What is ReactJS basics?
ReactJS Basics
ReactJS is a popular JavaScript library developed by Facebook for building user interfaces, particularly single-page applications (SPAs). It allows developers to create reusable UI components, manage the state efficiently, and build dynamic and interactive web applications with ease. Here are the fundamental concepts and features that constitute the basics of ReactJS:
1. Component-Based Architecture
React applications are built using components, which are the building blocks of the UI. Components can be functional or class-based and encapsulate their own structure, behavior, and styling. This modular approach promotes reusability and maintainability.
-
Functional Components: Defined as JavaScript functions that return JSX. They are simpler and easier to read.
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; }
-
Class Components: Defined using ES6 classes, they can manage their own state and lifecycle methods.
class Greeting extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } }
2. JSX (JavaScript XML)
JSX is a syntax extension that allows you to write HTML-like code within JavaScript. It makes the code more readable and expressive by visually representing the UI structure.
-
Example:
const element = <h1>Hello, World!</h1>;
-
Transpilation: JSX is transpiled to JavaScript using tools like Babel, converting it into
React.createElement
calls.const element = React.createElement('h1', null, 'Hello, World!');
3. Virtual DOM
React uses a Virtual DOM, which is an in-memory representation of the actual DOM. When the state of a component changes, React updates the Virtual DOM first, calculates the difference (diffing), and then efficiently updates only the necessary parts of the real DOM. This optimizes performance and ensures fast rendering.
4. Props (Properties)
Props are read-only inputs passed from parent to child components. They allow data to flow down the component hierarchy and enable components to be dynamic and reusable.
- Example:
function Welcome(props) { return <h1>Welcome, {props.name}!</h1>; } // Usage <Welcome name="Alice" />
5. State
State is a dynamic data structure that allows components to manage and respond to changes over time. Unlike props, state is managed within the component and can be updated using setState
in class components or the useState
Hook in functional components.
-
Class Component State:
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); } render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }
-
Functional Component State with Hooks:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
6. Lifecycle Methods and Hooks
React components go through different phases: mounting, updating, and unmounting. Class components use lifecycle methods like componentDidMount
, componentDidUpdate
, and componentWillUnmount
to perform actions at specific points. Functional components achieve similar functionality using Hooks.
- useEffect Hook: Handles side effects in functional components, replacing several lifecycle methods.
import React, { useState, useEffect } from 'react'; function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Empty dependency array means this runs once after initial render return ( <div> {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'} </div> ); }
7. Event Handling
React handles events using camelCase syntax and passes event handlers as functions rather than strings.
- Example:
function Button() { const handleClick = () => { alert('Button clicked!'); }; return <button onClick={handleClick}>Click Me</button>; }
8. Conditional Rendering
React allows you to render components or elements conditionally based on certain conditions, using JavaScript operators like if
, &&
, and ternary ? :
.
- Example:
function Greeting(props) { const isLoggedIn = props.isLoggedIn; return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} </div> ); }
9. Lists and Keys
Rendering lists of elements in React requires using the map
function and assigning a unique key
to each item to help React identify which items have changed, been added, or removed.
- Example:
function TodoList(props) { return ( <ul> {props.todos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> ); }
10. Forms
Handling forms in React involves managing form data through state, using controlled components where form elements derive their values from state and update state on changes.
- Example:
import React, { useState } from 'react'; function NameForm() { const [name, setName] = useState(''); const handleSubmit = (e) => { e.preventDefault(); alert(`Hello, ${name}!`); }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> </label> <button type="submit">Submit</button> </form> ); }
11. Routing
While not part of React core, routing is essential for building SPAs. React Router is the most popular library for handling routing in React applications, enabling navigation between different components without reloading the page.
- Example:
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; } function App() { return ( <Router> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); } export default App;
12. State Lifting
When multiple components need to share the same state, the state is "lifted" up to their closest common ancestor. This ensures a single source of truth and consistent data flow.
- Example:
function Parent() { const [value, setValue] = useState(''); return ( <div> <ChildA value={value} setValue={setValue} /> <ChildB value={value} /> </div> ); } function ChildA({ value, setValue }) { return <input value={value} onChange={(e) => setValue(e.target.value)} />; } function ChildB({ value }) { return <p>Value: {value}</p>; }
13. React Developer Tools
React provides browser extensions like React Developer Tools for Chrome and Firefox, which help in inspecting the component hierarchy, state, and props in real-time, facilitating easier debugging and development.
Summary
ReactJS is a powerful library for building dynamic and efficient user interfaces through a component-based architecture, JSX, virtual DOM, and state management. Mastering these basic concepts lays a strong foundation for developing complex applications and advancing to more advanced topics in React.
GET YOUR FREE
Coding Questions Catalog