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.
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.
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
Advantage
Why
Huge ecosystem
Ready-made libraries for almost anything (routing, forms, animation, requests)
Job market
It's the most widely adopted frontend framework, which makes it easier to find jobs, tutorials and developers
Real componentization
Makes it easier to split large interfaces into testable, reusable pieces
Disadvantage
Why
Learning curve
JSX, hooks, and the very concept of "UI as a function of state" take some time to get used to
It's only the UI layer
Routing, 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 weight
Ships 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:
Framework
Main characteristic
React
UI-only library, JSX syntax, the broadest ecosystem on the market
Vue
Syntax considered closer to traditional HTML/CSS, generally a gentler learning curve
Svelte
Does the heavy lifting at build time, generating less code for the browser at runtime
Angular
Complete 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.
Share:
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".
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.
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
Vantagem
Por quê
Ecossistema enorme
Bibliotecas 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 real
Facilita dividir interfaces grandes em pedaços testáveis e reutilizáveis
Desvantagem
Por quê
Curva de aprendizado
JSX, hooks e o próprio conceito de "UI como função de estado" exigem um tempo de adaptação
É só a camada de UI
Roteamento, 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 extra
Carrega 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:
Framework
Característica principal
React
Biblioteca focada só na UI, sintaxe JSX, o ecossistema mais amplo do mercado
Vue
Sintaxe considerada mais próxima do HTML/CSS tradicional, curva de aprendizado geralmente mais suave
Svelte
Faz o trabalho pesado em tempo de build, gerando menos código para o navegador em tempo de execução
Angular
Framework 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.
Compartilhar:
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.