Skip to Content
👆 We offer 1-on-1 classes as well check now
React.jsGetting StartedYour First Component

Your First Component

Welcome to React 19, a powerful JavaScript library for building user interfaces. In this guide, we’ll help you create your first React component. React components are the building blocks of any React application, and understanding how to create them is essential for any React developer.

Basic Example

Let’s start with a simple example. A React component is a JavaScript function that returns JSX (JavaScript XML) elements. Here’s an example of a basic “Hello World” component:

import React from 'react'; function HelloWorld() { return <h1>Hello, World!</h1>; }

In this example, we define a HelloWorld function that returns an <h1> element with the text “Hello, World!”. We can then use this component in our React application like any other JSX element.

Advanced Usage

Let’s create a more complex example, a Counter component that displays a count and allows the user to increment or decrement it:

import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count - 1)}>Decrement</button> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }

In this example, we use the useState hook to create a state variable count and an setCount function to update it. We then use this state to display the current count and update it when the user clicks the increment or decrement buttons.

Here’s another example that demonstrates how to use React 19’s new features, such as the use keyword for hooks:

import React from 'react'; function UserName() { const name = useUserName(); // assuming useUserName is a custom hook return <p>Hello, {name}!</p>; }

Best Practices

When creating React components, keep the following best practices in mind:

  • Keep your components small and focused on a single task.
  • Use meaningful and descriptive names for your components and variables.
  • Use JSX to create your component’s UI, rather than using JavaScript to manipulate the DOM directly.
  • Use React hooks, such as useState and useEffect, to manage your component’s state and side effects.

Key Takeaways

  • React components are the building blocks of any React application.
  • Components can be defined as functions or classes, and can use JSX to create their UI.
  • Use React hooks, such as useState and useEffect, to manage your component’s state and side effects.
  • Keep your components small, focused, and well-named, and use JSX to create their UI.
Last updated on