You can use the `useState` hook to manage state in functional components.
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <h1>{count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
You can use `useState` multiple times to manage different pieces of state in a functional component.
import React, { useState } from 'react'; const Form = () => { const [name, setName] = useState(''); const [age, setAge] = useState(''); return ( <div> <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" /> <input value={age} onChange={(e) => setAge(e.target.value)} placeholder="Age" /> </div> ); };
Props allow you to pass data from a parent component to a child component.
const ParentComponent = () => { return <ChildComponent name="John" />; }; const ChildComponent = (props) => { return <h1>Hello, {props.name}</h1>; };
You can pass multiple props to a child component by providing multiple attributes.
const ParentComponent = () => { return <ChildComponent name="John" age={30} />; }; const ChildComponent = (props) => { return <div> <h1>Hello, {props.name}</h1> <p>Age: {props.age}</p> </div> };
State is managed within a component, while props are used to pass data to child components. State is mutable, whereas props are immutable.
const Counter = (props) => { const [count, setCount] = useState(0); return ( <div> <h1>{count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> <p>Props value: {props.value}</p> </div> ); };
To summarize: State is local and can be changed, while props are passed down from parent components and cannot be changed by the child.
const ParentComponent = () => { const value = 10; return <ChildComponent value={value} /> }; const ChildComponent = (props) => { return <div> <p>State is local and mutable; Props are passed down and immutable.</p> </div> };
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!