React is a popular JavaScript library for building user interfaces, particularly for single-page applications where you want to create interactive and dynamic user experiences. Here are some main core concepts you need to know about React:

Components:

  • React applications are built using components, which are self-contained and reusable pieces of code that represent a part of the user interface.
  • Components can be class components or functional components. With the introduction of hooks in React, functional components are now more powerful and commonly used.

JSX (JavaScript XML):

  • JSX is a syntax extension for JavaScript that looks similar to XML or HTML. It allows you to write HTML elements and components in your JavaScript code, making it easier to visualize and understand the structure of your UI.
// Functional Component
const WelcomeMessage = () => {
  return <h1>Hello, Welcome to React!</h1>;
};

// Rendering the component
ReactDOM.render(<WelcomeMessage />, document.getElementById('root'));

Virtual DOM:

  • React uses a virtual DOM to improve performance. Instead of directly updating the actual DOM for every state change, React creates a virtual representation of the DOM in memory and updates it efficiently. Then, it calculates the difference (diffing) between the virtual DOM and the actual DOM, and only applies the necessary changes.

Props (Properties):

  • Components can receive data through props, which are similar to function arguments. Props allow you to pass data from a parent component to a child component.
// Functional Component with Props
const Greeting = (props) => {
  return <p>Hello, {props.name}!</p>;
};

// Rendering the component with props
ReactDOM.render(<Greeting name="John" />, document.getElementById('root'));

State:

  • State is a way to manage and track changes in a component. Unlike props, which are immutable, state is mutable and can be changed using the setState method. State changes trigger a re-render of the component.
// Class Component with State
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

// Rendering the component
ReactDOM.render(<Counter />, document.getElementById('root'));

Lifecycle Methods:

  • Class components have lifecycle methods that allow you to perform actions at different points in a component’s life, such as when it is mounted to the DOM or when it is about to be unmounted.
class LifecycleExample extends React.Component {
  componentDidMount() {
    console.log('Component has mounted');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return <p>Lifecycle Example</p>;
  }
}

// Rendering the component
ReactDOM.render(<LifecycleExample />, document.getElementById('root'));

Hooks:

  • Hooks are functions that allow functional components to use state and lifecycle features. useState is a common hook for managing state, and useEffect is used for handling side effects in functional components.
import React, { useState, useEffect } from 'react';

const CounterWithHooks = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Component has mounted');
    return () => console.log('Component will unmount');
  }, []); // Empty dependency array means this effect runs once on mount

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

// Rendering the component
ReactDOM.render(<CounterWithHooks />, document.getElementById('root'));

Event Handling:

  • React uses synthetic events to handle user interactions. Event handlers are similar to traditional JavaScript event handlers but are implemented in a way that works consistently across different browsers.

Conditional Rendering:

  • React allows you to conditionally render components or elements based on certain conditions. This is often done using JavaScript’s conditional statements or the ternary operator.
const ConditionalRendering = ({ isLoggedIn }) => {
  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome, User!</p>
      ) : (
        <p>Please log in to view this content.</p>
      )}
    </div>
  );
};

// Rendering the component
ReactDOM.render(
  <ConditionalRendering isLoggedIn={false} />,
  document.getElementById('root')
);

React Router:

  • For single-page applications with multiple views, React Router is commonly used to handle navigation and routing. It allows you to define routes and render different components based on the URL.

Understanding these core concepts is crucial for developing React applications efficiently and effectively. As you work with React, you’ll find that these concepts form the foundation for building scalable and maintainable user interfaces.

Tagged in:

,