React in a Nutshell

This page covers the essentials of React. A React component is simply a function that outputs HTML and manages its own state.

Counter.jsx

import { useState } from 'react'

const Counter = (props) => {
  const [count, setCount] = useState(0)

  // Callbacks
  const dec = prev => prev - 1
  const inc = prev => prev + 1
  const zero = () => 0

  return (
    <div>
      <p>The count is {count}, <strong>{props.word}</strong>.</p>
      <button onClick={() => setCount(dec)}>-</button>
      <button onClick={() => setCount(inc)}>+</button>
      <button onClick={() => setCount(zero)}>Reset</button>
    </div>
  )
}

export default Counter

App.jsx (the root component)

import Counter from './Counter.jsx'

const App = () => (
  <>
    <Counter word="first" />
    <Counter word="second" />
  </>
)

export default App