Components

React components are the building blocks of React applications. Components are functions that return a React element (JSX). They are easily reusable and can be composed to form more complex components. Components can be written as classes or functions. We only looked at functional components, so this is what I will use in the example code (and function components are the new way to write components).

Basic component

A basic counter component would look like this:

  import React from 'react';

export default function Component() {
  return (
    <article>
      <h1>Basic Component</h1>
      <ol>
        <li>This is a list element</li>
        <li>This list is in a React component</li>
        <li>It can be reused effortlessly</li>
      </ol>
    </article>
  )
}
  

State

State is a way to store data in a React component. Components use state to store data that changes over time. Every time the state changes, the component is re-rendered!

A simple example would be a counter component:

Takeaways

The takeaways for state management in React are:

  1. Use useState to store and modify state in a component.
  2. Do not use global variables as they might behave different from what is expected.
  3. Use useRef to store values that should not trigger a re-render.
  4. Lift state up to the parent component if it needs to be shared between components (might even be different components).
    1. Pass the state as a prop to the child component.
    2. Use createContext and useContext to pass context (Passing Data Deeply with Context).