React.js is a powerful JavaScript library for building user interfaces, and at its core are two essential concepts: state and props. Understanding these two concepts is crucial for anyone looking to develop dynamic and interactive React applications.
Props, short for properties, are read-only attributes that you pass from a parent component to a child component. They are used to pass data and event handlers down the component tree, enabling communication between components. Think of props as the way a parent component can provide input to a child component.
Example: Passing Props
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } function App() { return <Greeting name="Alice" />; }
In this example, the Greeting
component receives a prop called name
from the App
component. The Greeting
component then uses this prop to display a personalized message.
State, on the other hand, is a built-in object that allows components to create and manage their own data. State is mutable, meaning it can change over time, and this change can trigger a re-render of the component. State is local to the component in which it is declared and cannot be accessed by child components unless passed down as props.
Example: Using State
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); } function App() { return <Counter />; }
In this example, the Counter
component uses the useState
hook to create a count
state variable and a setCount
function to update it. Each time the button is clicked, setCount
is called, updating the count
state and causing the component to re-render with the new count value.