Props and  hooks in React JS

Props and hooks in React JS

Introduction

In this article we are going see some important topics in react.js including

  • ☝ Props
  • ✌ useState
  • 👌 useEffect

we will see these concepts with some examples.

Props in react.js

Props stands for properties. Props are object argument passed into React components (functional components and class components). Props are passed into components in the form of object through JSX(syntax extension to JS) attributes . React components accept this props and return a react element.

Example

// Card.jsx file
function Card(props){
 return <h1>{props.head}</h1>;
}
export default Card;

// App.js file
import Card from "./componets/Card";

function App(){
    return <Card head='REACT.JS'/>
}
export default App

Diagrammatic explanation of the above code

props.png

What is Hook?

  • Hooks are a new addition in React 16.8.
  • It allows us to use state and other React features without writing a class.
  • State is a built-in React object that is used to contain data or information about the component. A component's state can change over time. whenever it changes, the component re-renders.
  • In case of adding some states in functional components, previously we need to convert it to a class. Now with the help of hook we can directly add states in functional components.

Let's see 2 important types of hooks (useState , useEffect) here.

☝ useState() Hook

  • The state hook allows us to have state variables in functional components.
  • To use this hook in component we have to import useState from react. It will keep local state in functional component.

      import { useState } from 'react' 
    
  • useState hook accepts only one argument (default value) that is initial state. Argument may be any type of data like string, number, array, object etc..

  • It returns an array with two items. The first item is state variable, and the second is a function that updates state variable. To destructure the returned array square brackets[] are used.

    const [state, setState]=useState()
    

state.png

  • It is used to declare only one state variable. If we want more than one variable then we need to do multiple useState calls. State variable name may be anything.

Example for useState hook

import { useState } from 'react';

function Card({data}){
const[name, setName]=useState('React.JS');
return (
   <div className="card">
    <img src={data.src} alt="" />
    <h1>{name}</h1>  
    <button onClick={()=>setName(data.head)}>click</button>
   </div>
   )}

function App(){
    const detail={
        src:'https://www.patterns.dev/img/reactjs/react-logo@3x.svg',
        head:'useState hook'
    }
    return <Card data={detail}/>
}

// output
// initial output : <h1> React.JS </h1>
// after clicking button :<h1> useState hook </h1>

In the above example, Card is a functional component which has data object as props and inside this component, useState hook has returned state variable(name) and function (setName). Initial value of name variable is 'React.JS'. When we click the button the setName function will manipulate the value of name variable. This is how state hook is working in react.

🤞useEffect() Hook

The effect hook allows us to run side effects on functional components of react.

Use cases of effect hook?

useEffect is most commonly used to execute code when the component is.

  • rendered to the DOM for the first time (componentDidMount).
  • updated (componentDidUpdate).
  • unmounted->DOM produced by the component is removed (componentWillUnmount).

Side Effects

Some times we have to interact with outside world of our react components to do something. An action that impinges on the outside world in some way is called a side effect.

some common side effects includes

  • Working with timers like setInterval or setTimeout.
  • Fetching data.
  • To interact with browser APIs (that is, to use document or window directly).
  • setting up a subscription

useEffect() hook hepls us to handle these side effects in our projects.

Some side effects require cleanup( a way of stopping side effects that do not need to be executed anymore) and some don't need cleanup.

Effects Without Cleanup

In case of running some additional code after React has updated the DOM side effects will be handled without cleanup. Ex: manual DOM mutations.

Effects With Cleanup

  • In some cases the cleanup process are required. Ex: while handling setInterval function cleanup(clearInterval) is must , otherwise it will keep running.
    • To use the cleanup function, we need to return a function within the useEffect function.
    • The cleanup function will be called when the component is unmounted.

Why we need cleanup?

  • To avoid memory leaks
  • To optimize our applications for a good user experience
  • To prevent unexpected errors in our applications

Syntax for useEffect() hook

 import { useEffect } from 'react';

 useEffect(callback, dependency)

Effect hook will accept 2 arguments.

  • 🔶 First one is a callback function that handles side effects.
  • 🔶 Second argument is a list of dependencies of side-effects. It is an array includes props and state values . These values are immutable.

Options of dependency in useEffect()

depend.png

  1. It is optional. If it is not specified, the effect runs after each render.
  2. If it’s empty ([]), the effect runs once, after the initial render.
  3. If it contains the list of values, The effect runs after any of changes of these values.

Simple example for useEffect hook

import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    let interval = setInterval(() => setConut(count+1), 1000); 

    return () => {
      // setInterval cleared when component unmounts
      clearInterval(interval);
    }
  }, []);
}

Conclusion

In this article we have seen,

🔹Props, an argument passed to the react components to provide react elements.

🔹useState(), a hook with single argument is used to return state variable and a function which updates that state variable.

🔹useEffect(), one of the important hooks in react helps us to handle side effects in our functional components.

Declaring and initializing variables, passing inputs, handling events are some basic and crucial thinks for creating an app. I hope this article explains these things.

Thank you for reading..🤗😃