React Basics - anastasiamexa/react-complete-guide-course-resources GitHub Wiki

React is a JavaScript library for building user interfaces. Here are some of the fundamental concepts and basics of React:

1. Components:
In React, everything revolves around components. A component is a self-contained, reusable piece of user interface. Components can represent parts of a UI, such as buttons, forms, or entire pages.

  • Create a Custom Component:
    In your project directory, create a new file for your custom component. Let's call it Greeting.js. This component will receive a name prop and display a greeting message.
// Greeting.js
import React from 'react';

function Greeting(props) {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
    </div>
  );
}

export default Greeting;
  • Use the Custom Component:
    Now, you can use the Greeting component in another component or your App.js file. In this example, we'll use it in App.js.
// App.js
import React from 'react';
import Greeting from './Greeting';

function App() {
  return (
    <div>
      <h1>My Simple React App</h1>
      <Greeting name="John" />
    </div>
  );
}

export default App;
  • Rendering:
    In the App component, we import the Greeting component and use it like an HTML tag. We pass the name prop with the value "John" to the Greeting component.

2. JSX (JavaScript XML):
JSX is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. JSX makes it easy to define the structure of React components.
Example JSX code:

const element = <h1>Hello, React!</h1>;

3. Rendering:
You can render a React component using the ReactDOM.render() method. This method takes a React component and attaches it to a DOM element in your HTML file.
Example rendering a component:

ReactDOM.render(<App />, document.getElementById('root'));

4. Props (Properties):
Props are a way to pass data from a parent component to a child component. They are read-only and help make your components dynamic and reusable.
Example of using props:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// Usage
<Welcome name="John" />

5. State:
State is a mechanism for managing and updating data within a component. Unlike props, state is mutable and can be changed by the component itself. You can initialize state in a class component using the this.state object. In functional components, you can use the useState hook to manage state, it returns an array with 2 elements, the first is the current state value, the second is a function that allows us to update the state value.
Example using useState:

import React, {useState} from 'react';

function App() {
    const [price, setPrice] = useState(100);
    
    function clickHandler() {
        setPrice(75);
    }
    
    return (
        <div>
            <p>{price}</p>
            <button onClick={clickHandler}>Apply Discount</button>
        </div>
    );
}

export default App;

and using anonymous arrow function:

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>
  );
}

export default Counter;

6. Lifecycle Methods (Class Components):

  • In class components, you can use lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount to control component behavior at different stages of its lifecycle.
  • These methods allow you to perform tasks like fetching data from APIs or subscribing to external events.

7. Hooks (Functional Components):

  • Hooks were introduced in React to add state and other features to functional components. They include useState, useEffect, useContext, and more.
  • useEffect is commonly used for side effects like data fetching and subscribing to state changes in functional components.

8. Conditional Rendering:

  • React allows you to conditionally render components or content based on conditions using JavaScript expressions within JSX.
  • Example conditional rendering:
function Greeting(props) {
  if (props.isLoggedIn) {
    return <UserGreeting />;
  } else {
    return <GuestGreeting />;
  }
}

9. Event Handling:

  • React components can respond to user interactions through event handling. You can attach event handlers to JSX elements to trigger functions when events like clicks, changes, or submissions occur.
  • Example event handling:
function ButtonExample() {
  function handleClick() {
    alert('Button clicked!');
  }

  return <button onClick={handleClick}>Click Me</button>;
}

10. "Lifting state up":
"Lifting state up" is a common pattern in React for managing and sharing state between multiple components, especially when those components are hierarchically related. This pattern involves moving the state from child components to their common ancestor or a higher-level component in the component tree, making it a shared state accessible to those child components. This approach helps to maintain a single source of truth for the state and ensures that changes in one component can affect the state and behavior of other components.

Here's a step-by-step explanation of how "lifting state up" works:

  1. Identify the Shared State: First, you need to identify a piece of state that multiple child components need to access and modify. This state could be anything from form input values to more complex application data.
  2. Create a Parent Component: Create a parent or container component that will serve as a common ancestor for the child components. This parent component will hold the shared state.
  3. Pass State Down as Props: Pass the shared state down to the child components as props. Each child component receives the state as a prop and uses it for rendering or interacting with the state.
  4. Handle State Changes: When a child component needs to modify the shared state, it does not directly modify the state itself. Instead, it calls a function or invokes a callback provided by the parent component through props. This function allows the parent component to handle the state changes.
  5. Update the State in the Parent Component: In the parent component, you implement the logic for updating the shared state based on the callbacks provided by the child components. Since the state resides in the parent component, it can easily manage changes and propagate updates to all child components that depend on it.
  6. Re-render Child Components: When the state changes in the parent component, React automatically re-renders all the child components that depend on that state with the updated values.

Benefits of "Lifting State Up" pattern:

  • Centralized State: It promotes a centralized and predictable way of managing state, making it easier to understand and maintain.
  • Avoids Prop Drilling: It prevents the need for "prop drilling," which is passing state through multiple intermediary components just to reach a deeply nested component.
  • Maintainable Code: It results in more maintainable and scalable code since the state logic is concentrated in one place (the parent component).
  • Easier Testing: Testing becomes more straightforward because you can test each component in isolation, and state management is centralized.

In summary, "lifting state up" is a fundamental concept in React that helps maintain clean and predictable state management in your application by moving state and state-related logic to a common ancestor component. This pattern is especially valuable when dealing with shared data and complex component hierarchies.

11. Types of Components:

  1. Stateful Components (Class Components):
  • Use the class syntax and extend React.Component.
  • Can manage their own internal state using this.state.
  • Utilize lifecycle methods like componentDidMount, componentDidUpdate, etc.
  • Useful for complex state management, side effects, and legacy codebases.
  • Less commonly used in modern React applications due to the introduction of hooks.
  1. Stateless Components (Functional Components):
  • Defined as JavaScript functions that take props as input and return JSX.
  • Do not have internal state or lifecycle methods.
  • Are primarily used for presenting UI and rendering content.
  • Highly reusable and easy to understand.
  • Becoming the preferred choice for building React components, especially in modern React applications.
  1. Controlled Components:
  • Can be either stateful (class) or stateless (functional).
  • Manage the component's data (e.g., form input values) via React state.
  • Update data through user interactions (e.g., form submissions, button clicks).
  • Provide a controlled and predictable way to manage and validate user input.
  • Commonly used in forms and interactive user interfaces.

In summary, stateful components (class components) focus on managing internal state and lifecycle methods, stateless components (functional components) focus on rendering UI and are easy to understand, and controlled components manage user input and interactions via React state, making them suitable for forms and interactive components. The choice of which component type to use depends on the specific requirements of your application and the principles of modern React development. Functional components are the preferred choice for most scenarios in contemporary React applications, especially when used with hooks for managing state and side effects.

These are some of the core concepts in React. As you continue your React journey, you'll explore more advanced topics like routing, state management with Redux or Context, and integrating React with back-end services. React's component-based architecture and reactivity make it a powerful choice for building dynamic user interfaces in web applications.

⚠️ **GitHub.com Fallback** ⚠️