Gradient

Understanding Props and Hooks in React

Written ByAnsh Ajay Mishra
Published On2025-03-17
Understanding Props and Hooks in React

Understanding Props and Hooks in React

React is a powerful JavaScript library for building user interfaces. Two of the fundamental concepts in React are Props and Hooks. Understanding these will help you write reusable, efficient, and modern React applications.

What Are Props?

Props (short for properties) are used to pass data from a parent component to a child component in React. They are read-only and help make components reusable.

Example of Props:

function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}
 
function App() {
  return <Greeting name="Ansh" />;
}

Key Points About Props:

  • Props are immutable (cannot be changed by the child component).
  • They allow data to be passed down the component tree.
  • Useful for making components dynamic and reusable.

What Are Hooks?

Hooks are functions that let you use state and lifecycle features in functional components. They were introduced in React 16.8 to eliminate the need for class components in most scenarios.

Common React Hooks

  1. useState – Manages state in functional components.
  2. useEffect – Handles side effects in components.
  3. useContext – Provides global state management.
  4. useReducer – Alternative to useState for complex state logic.
  5. useRef – Accesses DOM elements and maintains values across renders.

Example of useState:

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>
  );
}

Example of useEffect:

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 function
  }, []);
 
  return <p>Time Elapsed: {seconds} seconds</p>;
}

Props vs Hooks

FeaturePropsHooks
PurposePass data from parent to childManage state and side effects
MutabilityImmutableMutable
ScopePassed between componentsUsed inside components
Example<Component name='John' />const [count, setCount] = useState(0);

When to Use Props and Hooks

  • Use Props when passing data from one component to another.
  • Use Hooks when managing component-level state and side effects.

Conclusion

Props and Hooks are essential for React development. Props allow components to communicate, while Hooks enable functional components to manage state and lifecycle events. Understanding their differences will help you build efficient and maintainable React applications.

Are you using Props and Hooks effectively in your React projects? Let me know your thoughts in the comments!

Gradient Background