Understanding React Components JSX and Hooks

Understanding React Components and JSX

Introduction to React Components

React Components are the fundamental building blocks of React applications. They encapsulate UI elements and their logic, making it easier to manage and reuse code. In this blog post, we’ll delve deeper into components, JSX, and the differences between functional and class components, including how Hooks have replaced many class lifecycle methods for building websites.

Also Check Setting Up ReactJs and NextJs Project

What are React Components?

React components are reusable pieces of code that represent a specific part of your UI. They can be either functional Components or Class based Components. Let us check a few differences between both functional components as well class components.

Note: Just make sure component names always start with Uppercase and other methods/variables should start with lowercase as it is the way to differentiate between Components and other code. It also keeps code structured for readability.

Functional Components

  • They are Simpler and often preferred for presentational components.
  • Defined as common functions that return JSX elements makes it easier to write a component.
  • Can have state and lifecycle methods (class based life cycle methods) using Hooks without much work. Hooks like UseEffect, UseState are the commonly used.
  • We can easily define and manage variables with hook as well consume APIs with lesser code.
  • Simpler components can be defined as one liner as well.

Example of a Functional Component:

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

Here props are used as an object to pass multiple values, and name is the one field in the object to greet the user. For example, if name is JOHN, it will show “Hello, JOHN!” on the screen for output.

Example of a one-line component with lambda expression. These are useful only when there is small code and should not have multiple logics as its not recommended.

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

Also Read, Right Way to Code Syntax like CamelCase and PascalCase to know

Class Components

  • They are more complex and can have state and lifecycle methods like componentDidMount, componentWillMount, and so on.
  • They are defined as classes that extend React.Component and may contain constructor as well with class methods known as lifecycle methods to intitalise and use variables and consume api.
  • Used for more complex components that require state management or custom lifecycle behavior.

Example of a Class Component:

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

Use of JSX in React Components

JSX is a syntax extension for JavaScript that allows you to write HTML-like structures within JavaScript code. It is compiled into regular JavaScript at build time. Can be used in both functional as well, class based components with newer React versions.

Example of JSX:

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

const RenderElement = () => <div>{element}</div>

The element is just a HTML fragment, where as RenderElement is a component wrapping the HTML code as well the fragment. We can use fragments to keep our complex logics separate.

Another difference you might have noticed Fragment is just a normal value assignment of HTML code, whereas Component is a function, that returns rendered UI.

Rendering React Components

To render a React component, you can simply return it from the render method of a parent component or directly in JSX.

Example of rendering a component:

function ParentComponent() {
  return (
    <div>
      <Greeting name="Alice" />
    </div>
  );
}

// This is how we use in another components
<ParentComponent />

Props in React Components

Props are used to pass data from parent components to child components. They are immutable(Not changing over time) and cannot be modified directly within the child component. They stay the same whether you change any other state value or not. Props can be passed as a string, number or an object.

Example of passing props:

<Greeting name="Bob" />

<Greeting user = {{"name": "Bob", "age":18}} />

The first prop is just a simple string whereas the other one is an object.

State in React Components

State is a mechanism for managing data within a React component. It allows components to store and update their own data. Values that need to be changed over time can be passed to the state variable and users can track the changed values by checking current state value.

Example of using state with Hooks:

function Counter() {
  const [count, setCount] = useState(0);

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

Lifecycle Methods vs. Hooks

Class components use lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount to perform side effects or manage state. We have to use multiple methods to check and update values over time. Also based on if we need to update UI or fetch data from API. That was kind of complex and if not configured well, caused memory leaks in the application.

Functional components use Hooks like useEffect to achieve similar functionality that contains internally the lifecycle but with proper implementation. Hooks provide a more declarative and easier-to-reason-about way to manage side effects and state in functional components. Hooks are simpler than lifecycle and with reduced code which makes use of Hooks easier as well loved by everyone over the Lifecycle methods.

For example, useEffect Hook combines componentDidMount, componentDidUpdate and componentWillUpdate lifecycle methods making the functionality easier and only updates component if there is an actual change, else it will move to next logic. This keeps state update in check and helps avoiding memory leaks.

Example of using useEffect:

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      setData(data);      
    };

    fetchData();
  }, []);

// This will only execute once as its an empty dependency array

  // ...
}

Check Lifecycle methods on React Docs

Check Hooks Usage on React Docs

Choosing Between Functional and Class Components

  • Functional components are generally preferred for most use cases due to their simplicity and the benefits of Hooks. Also, they are modern and starting React 16, they are the default and recommended for clean code and compatibility with new features.
  • Class components can still be used for complex components that require custom lifecycle methods or ref forwarding.

By understanding the differences between functional and class components, and how Hooks have replaced many class lifecycle methods, you can make informed decisions about which component type to use in your React applications. Let’s learn more in next articles. Stay connected and Thanks for reading our blog.

Content Protection by DMCA.com
Spread the love
Scroll to Top