Props and Hook

Props and Hook

In the 1st article of Step into React I've covered the required setup for React environment and stepped into Hello World. In this article, I'll primarily focus on React Props and Hook.

In React, props is a keyword which implies "Properties" and it's like a messenger, carrying information from one component to another within same application.

Let's try to understand it as you have to ask your father for an iPhone, but you can't directly ask him as he doesn't listen to you, so you went to your sister and asked her to request the same. Now your sister will pass your demand to your father, and as he looks at the demand list, he'll accept your demand, but indirectly.

So here, your sister is like a props who has passed your message to parents. There is the same functionality for props. It passes the data from one component to another.

Below are some properties of Props:

  • Data Passing: Props is used to pass data from a parent component to a child component within a React application.

  • Customization: It allows for the customization of child components based on the data or instructions passed from their parent.

  • Read-Only Nature: Props are immutable within the child component, meaning that they cannot be modified by the child.

  • Accessing Props: Inside a child component, props can be accessed using the props keyword.

  • Dynamic Behavior: Components can dynamically adapt to changes in data or UI because props enable them to update automatically when the data passed through props changes.

How to pass the data using Props?

There are two different ways to pass the data:

  • Using keyword: In this way we define our key and value inside parent component and then it's accessed using props.key to get the value.

    Example: There are two different components Main.js and Card.js .

    I've to pass my name, age and email from Main component to Card so card is defined in Card.js but is called in Main.js.

      //Main.js is calling Card Component by passing props value
      <Card name="Ritik" age="19" email="ritikraushan9534@gmail.com" />
    
      //Card component is ussing props
      function Card(props){
              return(
                <>
                  <h1>My name is: {props.name}</h1>
                  <p>I am {props.age} years old.</p>
                  <p>Contact me at {props.email} </p>
                </>
      }
    
  • Using object: In this way we either pass a variable holding a set of key and value or use object in place of props.

      //Main.js is calling Card Component
      <Card name="Ritik" age="19" email="ritikraushan9534@gmail.com" />
      function Card({name,age,email}){
              return(
                <>
                  <h1>My name is: {name}</h1>
                  <p>I am {age} years old.</p>
                  <p>Contact me at {email} </p>
                </>
      }
    

    Now I hope you would have gained a lot that how to pass the data from a parent component to a child component using props.

After learning about props, if I tell you a limitation of props, wouldn't you be angry? Have patience; this limitation is the gate of React Hook. Here we are able to pass the data manually, but just suppose if we have to show thousands of users's cards on our application, then is it possible to pass them all?

Hold on, hold on!! If you'd say I'm a hard coder, so I can write thousands of codes, then what about JSON data, where you need to change the value of prop for each card? This is why React developers introduced hooks.

Hook refers to a special function that allows us to use React features within functional components. It enables functional components to manage state, perform side effects, access context, and more.

Suppose you have now super power to express your demands in front of your parents.

There're various hooks but we'll majorly see useState and useEffect . Wherever you see a prefix use understand that it's a hook in React library.

  1. State Management: The useState hook allows functional components to hold state. We can't use the local variable to update UI so it gives a superpower to state variables to update the UI as soon as the value is updated. We have to first import { useState} from 'react'; to make in use of state variable.

    Syntax:const [variable, setFunction]=useStae("Default Value")

import { useState} from 'react';
const [count, setCount]=useState(0);
//to change the value of count we use
setCount(2);
  1. Effect Hook: The useEffect hook allows functional components to perform side effects. Side effects include things like data fetching or manually changing the DOM. The useEffect hook takes a function as its argument, which will be executed after every render. For each time the state variable is changed it renders the whole component.

    import {useEffect } from 'react';

    Syntax:useEffect(callbackFunction, [Dependency]);

    Here if we use don't use [ ](dependency) then the whole component will be rendered again and again and if we use null dependency ( [ ] ) then rendered once. Generally we use null dependency.

       useEffect(() => {
           myFunction();
         }, []);
    

    Rules of Hooks: Hooks have some rules that need to be followed:-

    • Hooks should only be called at the top level of a functional component or from another custom hook.

    • Hooks should always be called in the same order, meaning you shouldn't conditionally call hooks.

    • Hooks should only be called from functional components or other custom hooks, not from regular JavaScript functions.

Now lets try to use props and hook in some of real world use.

Example 1: Make a count increase and decrease button.

import React, { useState } from 'react';

function Count() {
    const [count, setCount] = useState(0);

    const increase = () => {
        setCount(count+1);
    };

    const decrease = () => {
        setCount(count-1);
    };

    return (
        <>
            <p style={{ display: "flex", justifyContent: "center", marginTop: "5vh" }}>Count: {count}</p>
            <div style={{ display: 'flex', justifyContent: 'center', marginTop: '5vh', padding: "5px" }}>
                <button onClick={increase}>Increase</button>
                <button style={{ marginLeft: "10px" }} onClick={decrease}>Decrease</button>
            </div>
        </>
    );
}

export default Count;

When I click on increase it increases the count and when I click on decrease it decreases the count.

We'll see more library of react in next article. Till then just keep learning and exploring.