Blog Details
Md. Sidul Islam Moon
10 Oct 2024
9 min read
React has completely changed the way we build web apps. It's fast, flexible, and super trendy in the development world. But to truly unlock the power of React, you need to understand two key concepts: State and Props. They’re the backbone of managing data in your app and making your components interactive.
Think of State as the brain of your component. It's where all the data lives, and it can change based on what your users do. When the state updates, your component re-renders automatically to reflect those changes.
Here's a simple example of how to use state in a React component using the useState
hook:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initial state is 0
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example:
useState
to keep track of the count.count
holds the current state.setCount
is a function that updates the state.Every time you click the button, setCount
updates the count, and the component automatically re-renders!
While State is all about the internal data of a component, Props are like the gifts that keep on giving! They let you pass data from one component to another, making your components more dynamic and reusable.
Let's say you have a parent component that wants to send data to a child component. You can do this easily with props.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="React Developer" />;
}
export default App;
Here:
Greeting
is a child component that takes a name
as a prop.App
component passes the prop to Greeting
, and boom! The greeting message is personalized.Imagine building a social media app where you need to display a list of posts. You'd have a parent component responsible for fetching the data and child components that render each post. This is where props come into play like a boss!
function Post({ title, content }) {
return (
<div>
<h2>{title}</h2>
<p>{content}</p>
</div>
);
}
function Blog() {
const posts = [
{ id: 1, title: 'React is Awesome', content: 'React makes UI development fun!' },
{ id: 2, title: 'Learning Props', content: 'Props are the key to passing data.' },
];
return (
<div>
{posts.map((post) => (
<Post key={post.id} title={post.title} content={post.content} />
))}
</div>
);
}
export default Blog;
In this code:
Blog
is the parent component that holds the list of posts.Post
component receives the title and content of each post as props, making it super easy to reuse.React components go through a life journey that can be broken down into three main phases:
Let’s take a closer look at how to work with these phases using React Hooks.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
console.log('Component mounted');
const interval = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
return () => {
console.log('Component unmounted');
clearInterval(interval); // Cleanup when the component unmounts
};
}, []);
return <h2>Time: {seconds}s</h2>;
}
export default Timer;
In this example:
useEffect
hook runs once when the component mounts, setting up a timer.This is how you handle side effects in your components, like fetching data or subscribing to updates.
Let’s create a fun project that brings everything together—a To-Do List app! This will help you understand how state and props work together to create interactive components
import React, { useState } from 'react';
function TodoItem({ todo, onDelete }) {
return (
<li>
{todo.text}
<button onClick={() => onDelete(todo.id)}>Delete</button>
</li>
);
}
function TodoList() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
const addTodo = () => {
setTodos([...todos, { id: Date.now(), text: input }]);
setInput('');
};
const deleteTodo = (id) => {
setTodos(todos.filter((todo) => todo.id !== id));
};
return (
<div>
<h2>My To-Do List</h2>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Add a new task"
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} onDelete={deleteTodo} />
))}
</ul>
</div>
);
}
export default TodoList;
In this to-do list app:
Understanding State and Props is the key to mastering React and building interactive web apps that engage your users. Once you get the hang of them, you’ll be creating components that are not only smart but also flexible and reusable.
So, get your hands dirty with some code, and soon you'll be a React wizard! Keep coding and keep building amazing things with React!
Don’t worry, we don’t spam!