Key Concepts
1. Components
Components are the building blocks of React applications. They allow you to split the UI into reusable, independent pieces.
Types of Components:
- Functional Components: Simple JavaScript functions that return JSX.
- Class Components: ES6 classes that extend
React.Component(used less often now due to Hooks).
Example of a Functional Component:
function Greeting() { return <h1>Hello, React!</h1>;}2. Props
Props are short for properties. They are used to pass data from a parent component to a child component. They enable component reusability.
function Welcome(props) { return <h1>Welcome, {props.name}!</h1>;}
// Usage:<Welcome name="Alice" />;3. State
State is like a container where React stores information (data) about a component. This information can change while the app is running. For example, if you’re building a counter, the number you’re counting is stored in the state. When the state changes, React automatically updates the part of the screen that needs to show the new data. This makes it easy to keep your app’s interface in sync with the data.
Think of it like this: If your app is a whiteboard, state is the marker—every time you write or erase something, the whiteboard (your app) updates what it shows.
Counter Example
import { useState } from "react";
function Counter() { const [count, setCount] = useState(0);
return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> );}4. Hooks
Hooks are functions that let you use state and other React features in functional components. They were introduced in React 16.8.
Before hooks, React had class components to manage state and lifecycle methods, but now, with hooks, you can do all of this in simpler functional components.
Common Hooks:
useState: Manages state in a functional component.useEffect: Allows you to run code after the component renders, like fetching data or updating the page title.useContext: Allows you to use data from React’s Context API without needing to pass props down manually.
Remember:
- Hooks only work inside
functional components. - Hooks must follow the
rules of hooks, like calling them at the top level of a component.
import { useState, useEffect } from "react";
function Timer() { const [seconds, setSeconds] = useState(0);
useEffect(() => { const interval = setInterval(() => { setSeconds((prev) => prev + 1); }, 1000);
return () => clearInterval(interval); // Cleanup }, []);
return <p>Timer: {seconds}s</p>;}