The Basics of React Components

On the React website, it says “components let you split the UI into independent, reusable pieces, and think about each piece in isolation.” What this essentially does is allow you to create your UI piece by piece. You can create components for a navbar, a footer, a drop down menu, a gallery of images, a button, etc. Almost anything you want represented on the DOM can have its own component or be contained within a component. The React docs describe components succinctly, saying “components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

A functional component is essentially a JavaScript function. This function can accept props from a parent component and returns a React element. A class component requires an extension from React and a render method that returns HTML. Without the use of hooks, class components are the only way to update state. Class components are also the only way to use React’s lifecycle methods like componentDidMount.

React’s lifecycle methods for reference

Function Components:

function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>

Class Components:

class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>

Both props and state contain information that influences the DOM. In React, state is an object that holds some information that has the possibility to change over the lifetime of the component. It’s a good idea to make state as simple as possible and minimize the number of class components. Props, short for properties, are data passed down from a parent component to a child component. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.

Now that we now the difference between props and state, and that state can be dynamic, it would be useful to know how to update state. State should never be updated directly because it won’t re-render the component.

// Don’t do thisthis.state.message = ‘Hello world’

Instead use setState() method. It schedules an update to a component’s state object. When state changes, the component responds by re-rendering.

// Do this!this.setState({ message: ‘Hello World’ })

I think I already knew most of this stuff already but it’s definitely necessary information to cover in order to gain a deeper understanding of React. Hopefully this will help someone newer to React get a good foundation of knowledge to build upon.