التخطي إلى المحتوى الرئيسي

Hook in React-JS | useEffect, useLayoutEffect, useContext, useMemo, useCallback, useState, useRef


If we want to implement the react-life cycle activities under the function component then react provides hooks. we do not call the hooks it will automatically call during component loading.

if we want to call the functionality during component update then we can call useEffect hooks, React provide multiple hooks method to implement hooks functionality in an application.

Hooks are similar to JavaScript functions, but you need to follow these two rules when using them. Hooks rule ensures that all the stateful logic in a component is visible in its source code. These rules are:

1. Only call Hooks at the top level

Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a components renders.

2. Only call Hooks from React functions

You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Hooks can also be called from custom Hooks.

Hooks State

Hook state is the new way of declaring a state in React app. Hook uses useState() functional component for setting and retrieving state. Let us understand Hook's state with the following example.
Now i am implementig useState() to intialize the value


import React, { useState } from 'react';  
  
function App() {  
  // Declare a new state variable, which we'll call "count"  
  const [countsetCount] = useState(0);  
  
  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  


export default App;

React Hooks

In the above example, useState is the Hook which needs to call inside a function component to add some local state to it. The useState returns a pair where the first element is the current state value/initial value, and the second one is a function that allows us to update it. After that, we will call this function from an event handler or somewhere else. The useState is similar to this.setState in class. The equivalent code without Hooks looks like as below.



import React, { useState } from 'react';  
  
class CountApp extends React.Component {  
  constructor(props) {  
    super(props);  
    this.state = {  
      count: 0  
    };  
  }  
  render() {  
    return (  
      <div>  
        <p><b>You clicked {this.state.count} times</b></p>  
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>  
          Click me  
        </button>  
      </div>  
    );  
  }  
}  

export default App;

Hooks Effect

The Effect Hook allows us to perform side effects (an action) in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.

Side effects have common features which the most web applications need to perform, such as:

Updating the DOM,

Fetching and consuming data from a server API,

Setting up a subscription, etc.

Let us understand Hook Effect with the following example.



import React, { useState } from 'react';  
  
import React, { useStateuseEffect } from 'react';  
  
function CounterExample() {  
  const [countsetCount] = useState(0);  
  
  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {  
    // Update the document title using the browser API  
    document.title = `You clicked ${count} times`;  
  });  
  
  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export de
export default App;

Custom hooks:-

we can create our own hooks function, it will cal the user defined hooks.

import React, { useStateuseEffect } from 'react';  
const useDocumentTitle = title => {  
  useEffect(() => {  
    document.title = title;  
  }, [title])  
}    
function App() {  
  const [countsetCount] = useState(0);  
  const incrementCount = () => setCount(count + 1); 
  useDocumentTitle(`You clicked ${count} times`);  
  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={incrementCount}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export default App;




Another Hooks Example
useMemo Example:

This hooks store output data of function under cache(memoize), that can not changed if
dependency array will not be changed.

it can re-render function if dependency will be changed.

useCallback is just opposite of it's because it contain function reference under cache.
if dependency change then also it not re-render function.

if we want to create static function from parent to child component then we create
useCallback based hook.

Example without dependency:

import { useState,useMemo, useCallback, useEffect } from "react";

function calculate() {
    let result = 0;
    for (let i = 0; i < 1000000000; i++) {
      result += i;
    }
    return result;
  }
function UseMemoExample()
{
    const [count, setCount] = useState(0);
    const [dependentCount, setDependentCount] = useState(10);
  //  const value =useMemo(calculate,[dependentCount])
   const value= useMemo(calculate,[])
    return(
    <div className="App">
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <p>Count: {count}</p>
      <button onClick={() => setDependentCount(dependentCount+1)}>
      Increment Dependent Count
    </button>
    <p>Dependent Count: {dependentCount}</p>
     
    </div>)
}
export default UseMemoExample;


Example with dependancy:

import { useState,useMemo } from "react";
function calculate() {
    let result = 0;
    for (let i = 0; i < 1000000000; i++) {
      result += i;
    }
    return result;
  }
export default function MemoExample()
{
    const [count, setCount] = useState(0);
    const [dependentCount, setDependentCount] = useState(10);
    const value =useMemo(calculate,[dependentCount]);
    return(
    <div className="App">
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <p>Count: {count}</p>
      <button onClick={() => setDependentCount(dependentCount + 1)}>
      Increment Dependent Count
    </button>
    <p>Dependent Count: {dependentCount}</p>
     
    </div>
    )

}

Example of useCallback:

import { useState,useMemo } from "react";
function calculate() {
    let result = 0;
    for (let i = 0; i < 1000000000; i++) {
      result += i;
    }
    return result;
  }
export default function MemoExample()
{
    const [count, setCount] = useState(0);
    const [dependentCount, setDependentCount] = useState(10);
    const value =useCallback(calculate,[dependentCount]);
    return(
    <div className="App">
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <p>Count: {count}</p>
      <button onClick={() => setDependentCount(dependentCount + 1)}>
      Increment Dependent Count
    </button>
    <p>Dependent Count: {dependentCount}</p>
     
    </div>
    )

}



                                                                                    

تعليقات

المشاركات الشائعة من هذه المدونة

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...