ReactJS Foundation
Making React Components Play Nice: Hooks, Props and Reusability Explained
Table of contents
Hey there, React Explorers!
Embarking on a React journey? Wondering about hooks, props, and the magic of reusable components? You're in the right place.
In the vibrant world of React development, a trio of concepts reign supreme: hooks, props, and component reusability. They form the backbone of building robust, flexible, and maintainable applications.
Let's grasp the concepts of each through practical examples.
Hook (useState):
Ah, the secret sauce! Hooks let functional components tap into state and lifecycle features previously exclusive to class components. Want to manage state or tap into the component lifecycle of a functional component? Hooks have your back!
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>
);
}
useState
is a hook in React that allows functional components to manage state. It initializes a state variable (count
in this example) and a function (setCount
) to update that state. The component re-renders when setCount
is called.
Prop:
Consider them to be messengers. They transfer data between the various parts of your application. Do you need a component to show a certain message? It happens because of the props!
import React from 'react';
function Greetings(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Greetings name="Alice" />
<Greetings name="Bob" />
</div>
);
}
Props (short for properties) are inputs passed to React components. In this example, the Greetings
component receives a name
prop to customize the displayed greeting message. Props allow components to be configurable and reusable.
Component Reusability:
import React from 'react';
function Button(props) {
return <button onClick={props.onClick}>{props.label}</button>;
}
function App() {
const handleClick = () => {
alert('Button clicked!');
};
return (
<div>
<Button label="Click me" onClick={handleClick} />
<Button label="Submit" onClick={handleClick} />
</div>
);
}
Component reusability refers to designing components that can be used multiple times across an application. The Button
component in this example is reusable—it receives different labels and onClick functions as props, allowing it to be reused without duplicating code. Reusable components enhance code maintainability and efficiency.
Props vs Hooks
Feature | Props | Hooks |
Mutability | Immutable | Mutable |
Scope | Passed down from parent to child | Defined within the component |
Access to state | No | Yes |
Access to side effects | No | Yes |
Access to other React features | No | Yes |
This table highlights the key differences between hooks and props concepts in React development.
ThankYou.