Components are the fundamental building blocks of React applications. Think of Instagram's feed as an example - each post you see is actually a reusable component. Let me break this down:
function Post({ author, content, likes, comments }) {
return (
<div className="post">
<PostHeader author={author} />
<PostContent content={content} />
<EngagementBar likes={likes} />
<CommentSection comments={comments} />
</div>
);
}
The postcard can serve as a major component that nests other components mentioned earlier. This component-based approach offers several advantages:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Controlled Components
If a component contains a form and its input fields are controlled by React state (useState) instead of useRef, it is a controlled component.
function ControlledInput() {
const [text, setText] = useState("");
return <input value={text} onChange={(e) => setText(e.target.value)} />;
}
Uncontrolled Component
If a component contains a form and its input fields are controlled using useRef instead of React state, it is an uncontrolled component.
function UncontrolledInput() {
const inputRef = useRef();
return <input ref={inputRef} />;
}
useRef).