← Back to Cooldecode
Cooldecode · Lesson 04 · Main track

Introduction to React: components, JSX, state and props

Last lesson we looked at when it's worth trading plain HTML/CSS/JS for a framework. Today we actually get into the most popular one: React. The goal here isn't to memorize syntax, but to understand the mental model behind it — because that same model, with variations, repeats across almost every modern frontend framework.

01What React actually is

React is a JavaScript library for building interfaces. It's not a new language or a complete "batteries included" framework — it's a focused piece that solves one specific problem: describing what the screen should look like given a state, and automatically taking care of updating the DOM when that state changes.

The core idea

Instead of telling the browser step by step "grab this element, change this text, hide that other one" (the imperative way of vanilla JS), you describe the final result you want on screen for every possible state of the application. React figures out the difference between what's on screen now and what should be there, and applies only the necessary changes to the DOM.

02Components: the basic unit

A component is a JavaScript function that receives input data and returns the description of a piece of interface. A whole screen gets assembled by composing smaller components, like Lego pieces: a Button, a ProductCard, an ItemList that uses several ProductCards inside it.

That composition is what makes React interesting in large projects: a well-isolated component can be reused across screens, tested on its own, and changed without breaking the rest of the app — as long as its boundaries (what it receives and what it returns) stay clear.

03JSX: why the syntax looks like HTML inside JS

JSX is a JavaScript syntax extension that lets you write something that looks like HTML directly inside your code. Browsers don't understand it natively — a build tool (like Babel, usually already bundled into any React setup) translates JSX into regular JavaScript function calls before the code reaches the browser.

function Greeting() {
  return <h1>Hello, world</h1>;
}

// what the JSX above actually becomes, under the hood:
function Greeting() {
  return React.createElement('h1', null, 'Hello, world');
}

The reason it exists is purely practical: describing the structure of an interface in plain JavaScript, without JSX, is verbose and hard to read. JSX keeps the code close to the visual result it produces, which makes it much easier to understand an interface just by glancing at the component.

04Props: how a component receives data

Props (short for "properties") are the data a component receives from whoever is using it — they work like a function's parameters. A component can't change its own props; they always flow from outside in, from a "parent" component to a "child" component.

function ProductCard({ name, price }) {
  return (
    <div className="card">
      <h3>{name}</h3>
      <p>${price}</p>
    </div>
  );
}

// usage:
<ProductCard name="Running shoes" price="299" />
<ProductCard name="Thermal bottle" price="89" />

The same ProductCard component is reused to display different products, each with its own data. That's the essence of reuse: write the visual structure once, feed it different data as many times as needed.

05State: how a component keeps its own memory

While props come from outside, state is a component's own internal memory — data that can change over time, usually in response to a user action (a click, typing, an API response). When state changes, React re-renders the component automatically to reflect the new value on screen.

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

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

useState is a "hook" — a special React function that gives a component the ability to have its own memory. Every call to setCount tells React that this piece of the interface needs to be recalculated, and React decides on its own the most efficient way to update the DOM.

06Props vs state, side by side

Props

Come from outside, from a parent component. Read-only for whoever receives them. Change when the parent decides to pass different values.

State

Belong to the component itself. Can be changed by the component, usually in response to an event. Every change triggers a new render.

07Pros and cons of React

AdvantageWhy
Huge ecosystemReady-made libraries for almost anything (routing, forms, animation, requests)
Job marketIt's the most widely adopted frontend framework, which makes it easier to find jobs, tutorials and developers
Real componentizationMakes it easier to split large interfaces into testable, reusable pieces
DisadvantageWhy
Learning curveJSX, hooks, and the very concept of "UI as a function of state" take some time to get used to
It's only the UI layerRouting, API calls and project structure don't come built in — every team assembles its own toolset (or uses a framework like Next.js on top)
Extra weightShips the React library to the browser, which doesn't make sense for simple, static pages

08Quick comparison with alternatives

React isn't the only option for building declarative interfaces. It's worth knowing where it fits relative to the best-known competitors:

FrameworkMain characteristic
ReactUI-only library, JSX syntax, the broadest ecosystem on the market
VueSyntax considered closer to traditional HTML/CSS, generally a gentler learning curve
SvelteDoes the heavy lifting at build time, generating less code for the browser at runtime
AngularComplete framework (not just the UI layer), more opinionated about project structure, common in large enterprise applications

In practice, the concepts of component, props and state (under different names) show up in all of them. Understanding React deeply makes it much easier to pick up any of the others later.

To remember

React solves the problem of keeping the screen in sync with the application's data, trading manual DOM manipulation for a declarative description of the interface. Components are the unit of reuse, props are the data coming in from outside, and state is the memory the component itself controls. This trio — component, props, state — is the foundation for everything that comes next in React, including the more advanced hooks.

Newsletter

Learn what AI is creating for you. Don't get lost.

Get notified when a new deep dive or lesson goes up. No spam, just new posts.

Cooldecode · Lição 04 · Trilha principal

Introdução ao React: componentes, JSX, state e props

Na lição passada vimos quando vale a pena trocar HTML/CSS/JS puro por um framework. Hoje entramos de fato no mais popular deles: o React. A ideia aqui não é decorar sintaxe, e sim entender o modelo mental por trás — porque é esse modelo que se repete, com variações, em praticamente todo framework de frontend moderno.

01O que é o React, de fato

React é uma biblioteca JavaScript para construir interfaces. Não é uma linguagem nova nem um framework completo "com tudo incluso" — é uma peça focada em resolver um problema específico: descrever como a tela deve se parecer, dado um estado, e cuidar de atualizar o DOM automaticamente quando esse estado muda.

A ideia central

Em vez de você dizer passo a passo "pegue este elemento, mude este texto, esconda aquele outro" (o jeito imperativo do vanilla JS), você descreve o resultado final que quer ver na tela para cada possível estado da aplicação. O React se encarrega de calcular a diferença entre o que está na tela agora e o que deveria estar, e aplica só as mudanças necessárias no DOM.

02Componentes: a unidade básica

Um componente é uma função JavaScript que recebe dados de entrada e retorna a descrição de um pedaço de interface. Uma tela inteira é montada compondo componentes menores, como peças de Lego: um Botao, um CardDeProduto, uma ListaDeItens que usa vários CardDeProduto dentro dela.

Essa composição é o que torna o React interessante em projetos grandes: um componente bem isolado pode ser reaproveitado em várias telas, testado sozinho e alterado sem quebrar o resto da aplicação — desde que seus limites (o que ele recebe e o que ele retorna) fiquem claros.

03JSX: por que a sintaxe parece HTML dentro do JS

JSX é uma extensão de sintaxe do JavaScript que permite escrever algo parecido com HTML diretamente dentro do código. Ele não é entendido nativamente pelo navegador — uma ferramenta de build (como o Babel, geralmente já embutido em qualquer setup de React) traduz o JSX para chamadas de função JavaScript comuns antes de o código chegar ao navegador.

function Saudacao() {
  return <h1>Olá, mundo</h1>;
}

// o que o JSX acima realmente se torna, por baixo:
function Saudacao() {
  return React.createElement('h1', null, 'Olá, mundo');
}

O motivo de existir é puramente prático: descrever a estrutura de uma interface em JavaScript puro, sem JSX, é verboso e difícil de ler. O JSX deixa o código parecido com o resultado visual que ele produz, o que ajuda bastante a entender a interface só de olhar o componente.

04Props: como um componente recebe dados

Props (de "properties") são os dados que um componente recebe de quem o está usando — funcionam como os parâmetros de uma função. Um componente não pode alterar suas próprias props; elas fluem sempre de fora para dentro, de um componente "pai" para um componente "filho".

function CardDeProduto({ nome, preco }) {
  return (
    <div className="card">
      <h3>{nome}</h3>
      <p>R$ {preco}</p>
    </div>
  );
}

// uso:
<CardDeProduto nome="Tênis de corrida" preco="299" />
<CardDeProduto nome="Garrafa térmica" preco="89" />

O mesmo componente CardDeProduto é reaproveitado para exibir produtos diferentes, cada um com seus próprios dados. Essa é a essência da reutilização: escrever a estrutura visual uma vez, alimentá-la com dados diferentes quantas vezes for preciso.

05State: como um componente guarda memória própria

Enquanto props vêm de fora, state (estado) é a memória interna de um componente — dados que podem mudar ao longo do tempo, geralmente como resposta a uma ação do usuário (um clique, uma digitação, uma resposta de API). Quando o state muda, o React re-renderiza o componente automaticamente para refletir o novo valor na tela.

function Contador() {
  const [contador, setContador] = useState(0);

  return (
    <div>
      <p>Valor atual: {contador}</p>
      <button onClick={() => setContador(contador + 1)}>
        Incrementar
      </button>
    </div>
  );
}

useState é um "hook" — uma função especial do React que dá a um componente a capacidade de ter memória própria. Cada chamada de setContador avisa ao React que esse pedaço da interface precisa ser recalculado, e o React decide sozinho a forma mais eficiente de atualizar o DOM.

06Props vs state, lado a lado

Props

Vêm de fora, de um componente pai. São somente leitura para quem as recebe. Mudam quando o pai decide passar valores diferentes.

State

Pertencem ao próprio componente. Podem ser alteradas por ele mesmo, geralmente em resposta a um evento. Cada mudança dispara uma nova renderização.

07Prós e contras do React

VantagemPor quê
Ecossistema enormeBibliotecas prontas para quase qualquer necessidade (roteamento, formulários, animações, requisições)
Mercado de trabalhoÉ o framework de frontend mais adotado, o que facilita encontrar vagas, tutoriais e desenvolvedores
Componentização realFacilita dividir interfaces grandes em pedaços testáveis e reutilizáveis
DesvantagemPor quê
Curva de aprendizadoJSX, hooks e o próprio conceito de "UI como função de estado" exigem um tempo de adaptação
É só a camada de UIRoteamento, chamadas de API e organização de projeto não vêm prontos — cada equipe monta seu próprio conjunto de ferramentas (ou usa um framework como o Next.js por cima)
Peso extraCarrega a biblioteca do React no navegador, o que não faz sentido para páginas simples e estáticas

08Comparação rápida com alternativas

React não é a única opção para construir interfaces declarativas. Vale saber onde ele se encaixa em relação aos concorrentes mais conhecidos:

FrameworkCaracterística principal
ReactBiblioteca focada só na UI, sintaxe JSX, o ecossistema mais amplo do mercado
VueSintaxe considerada mais próxima do HTML/CSS tradicional, curva de aprendizado geralmente mais suave
SvelteFaz o trabalho pesado em tempo de build, gerando menos código para o navegador em tempo de execução
AngularFramework completo (não só a camada de UI), mais opinativo sobre estrutura de projeto, comum em aplicações corporativas grandes

Na prática, os conceitos de componente, props e state (com nomes diferentes) aparecem em todos eles. Entender React a fundo facilita bastante aprender qualquer um dos outros depois.

Para fixar

React resolve o problema de manter a tela sincronizada com os dados da aplicação, trocando manipulação manual do DOM por uma descrição declarativa da interface. Componentes são a unidade de reuso, props são os dados que entram de fora, e state é a memória que o próprio componente controla. Esse trio — componente, props, state — é a base para tudo que vem depois no React, incluindo os hooks mais avançados.

Newsletter

Saiba o que a IA está criando pra você. Não fique por fora.

Seja avisado quando eu postar uma imersão ou lição nova. Sem spam, só posts novos.