When I first started learning React, the most important idea was that everything is a component. Components are reusable, independent pieces of UI that make building complex apps much easier.
In this post, let’s go through React components with a simple To-Do App example.
In this post, let’s go through React components with a simple To-Do App example.
function Welcome() {
return Hello, React!
;
}
This small piece of code is a full React component.
Class components were the standard before hooks.
function TodoItem({ text }) {
return {text} ;
}
They had lifecycle methods like do componentDidMount..
Simple and stateless (before hooks came).
# Store data
Rails.cache.write("user_#{user.id}_posts", user.posts, expires_in: 10.minutes)
# Read data
posts = Rails.cache.fetch("user_#{user.id}_posts") do
user.posts.to_a
end
Today, with hooks, functional components do everything.
import React, { useState } from "react";
function App() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState("");
const addTodo = () => {
if (newTodo.trim() === "") return;
setTodos([...todos, newTodo]);
setNewTodo("");
};
return (
My To-Do App
setNewTodo(e.target.value)}
placeholder="Add a task"
/>
{todos.map((todo, index) => (
))}
);
}
function TodoItem({ text }) {
return {text} ;
}
export default App;
Components = building blocks of React apps.
Props = how data flows into components.
State = how components manage data internally.
Functional components + hooks = modern React.
When I first built a to-do app in React, it felt magical to see data update instantly without refreshing the page. Even today, the same principles apply in large-scale apps: break things into smaller, reusable components.
Once you master components, everything else in React starts to make sense.