Sunday, 13 October 2024

React Hooks - custom Hook

 v CustomHook

Ø React allows us to create our own hook which is known as custom hook.

Example – 1 localStorage Demo

Step-1 Create folder name with hooks and add  file useLocalStorage.jsx and type rafce for adding basic component details

 

import from React, {useState, useEffect} from ‘react’;

const useLocalStorage = (key, initialValue) => {

        

const [name, setName] = useState(

            localStorage.getItem(key) ?

localStorage.getItem(key) : initialValue

);

useEffect(() => {

            localStorage.setItem(key, name)

},[name, key])

 

         return [name, setName]

}

export default useLocalStorage;

 

Step-2 Add reference in App.jsx file

 

import from React from ‘react’;

import ‘./App.css’;

import useLocalStorage from ‘./hooks/useLocalStorage’;

 

function App() {

 

         const [name, setName] = useLocalStorage(‘username’,’’);

const [id, setId] = useLocalStorage(‘userid’,’’)

 

 

 

 

         return(

            <>

<input type=”text” placeholder=”Name” value={name} onChange={(e) => setName(e.target.value)} />

<h2> Hello , {name}! </h2>

<input type=”text” placeholder=”Id” value={id} onChange={(e) => setId(e.target.value)} />

<h2> Your ID :  {id} </h2>

</>

);

}

export default App;




Example -2 useEffect with fetch demo

 

Step -1 Create new file useFetch.js

import { useState, useEffect } from "react";


const useFetch = (url) => {

const [data, setData] = useState(null);

 useEffect(() => {

    fetch(url)

      .then((res) => res.json())

      .then((data) => setData(data));

  }, [url]);

  return [data];

};

 export default useFetch;

 

Step -2 Add code in index.js

import ReactDOM from "react-dom/client";

import useFetch from "./useFetch";

 

const Home = () => {

const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");

 

  return (

    <>

      {data &&

        data.map((item) => {

          return <p key={item.id}>{item.title}</p>;

        })}

    </>

  );

};

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Home />);

React Hooks - useLayoutEffect

v useLayoutEffect Hook

Ø useLayoutEffect is used for measuring dom elements, animating dom elements, fixing flickering  issue, Api calling.

Ø useLayout Effect works similarly to useEffect but it is called before  the user Interface gets mounted.

Ø useEffect gets called after printing the dom elements. useLayoutEffect gets called before printing  the DOM elements

Ø For Example if you change colour of Dom Element using useState hook then it will display first dom element then after change color of dom element that will called blink or flicker issue. But when we change colour using useLayoutEffect then first it will change the colour and after that it will display dom element on the webpage.

 

Example :

Ø In below code useLayoutEffect function is after useEffect function but in console it will display before useEffect function. useLayoutEffect is executed before useEffect. So first useLayoutEffect is executed then display dom element and then after useEffect executed.

Ø useEffect called after mounting dom element and useLayoutEffect called before mounting dom element.

 

import React, { useEffect, useLayoutEffect } from ‘react’;

import ‘../App.css’;

 

function App() {

useEffect(() => {

            console.log(‘Message from useEffect’);

},[])

 

useLayoutEffect(() => {

            console.log(‘Message from useLayoutEffect’);

},[])

 

         return (

                     <>

                                 <h2>Test Message </h2>

                                

 

{

Array(40000).fill(‘’).map((item, index) =>(

   <li key={index}>

            {Math.pow(Math.random(),10)}

  </li>

))

}

</>

);

}

export default App;




React Hooks - useReducer

 v useReducer Hook

Ø useReducer is similar to useState, but instead of providing state and setter function, it provides state and dispatch function.

Ø The useReducer Hook accepts 2 arguments

i.)                 Reducer function

Specifies how the states gets updated.

ii.)              Initial State

And returns Current state and Dispatch method in array.

Ø When we use useState hook we directly update state variable value using setter function but when we use useReducer hook we can efficiently update  state variable value for different action.

 

            Example

          import React, { useState } from 'react'

          import { useReducer } from ‘react’

import './App.css'

import { useReducer } from ‘react’; 

function App() {

            const initialState = {count : 0}

            const reducer = (state, action) => {

                        switch(action.type) {

            case ’increase’ : {

                        return {count: state.count + 1}

}

case ’decrease’ : {

                        return {count: state.count - 1}

}

case ’input’ : {

                        return {count: action.payload}

}

default : {

            return state

}

}          

}

            const [state, dispatch] = useReducer(reducer, initialState)

return (

<> 

<h1 >{state.count} </h1>

<button onClick={()=>dispatch({type:’increase’})}>Increase</button>

<button onClick={()=> dispatch({type:’decrease’})}>Decrease</button>

<br/>

<input type=”number” value={state.count}

onChange={(e) => dispatch({type: ‘input’,payload:Number(e.target.value)})}/>

</ >

)

}

export default App



Sunday, 6 October 2024

React Hooks - useContext

Ø useContext is a react hook that allows you access data from any component without explicitly passing it down through props at every level.

Ø useContext is used to manage Global data in the react app.

Ø React Context is a way to manage state globally.

Ø It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.


The Problem

Ø State should be held by the highest parent component in the stack that requires access to the state.

Ø We have many nested components. The component at the top and bottom of the stack need access to the state.

Ø To do this without Context, we will need to pass the state as "props" through each nested component. This is called "prop drilling".





*    Steps to use context

Step :1 Create Context

Ø Create new folder context under src folder and add new file AppContext.jsx

 

import {createContext} from “react”;

export const AppContext = createContext();

const  ContextProvider =  (props) => {

      const phone = “1234567890”

      const name=”TestUser”

      return (

                  <AppContext.Provider value={{phone, name}}>

                              {props.children}

                  <AppContext.Provider>

)

}

export default ContextProvider

Step : 2 Providing Context

Ø Go to main.jsx and add below code

import React from ‘react’

import ReactDOM from 'react-dom/client'

import App from ' ./App.jsx'

import './index.css'

import ContextProvider from './context/AppContext.jsx'

 

ReactDOM. createRoot(document.getElementById( 'root')).render (

<ContextProvider>

<App />

</ContextProvider>

)

  

Step : 3 Consume Context

i.)  Create new file footer.jsx under components folder and type rafce which will generate code for basic react component.

 

import React from ‘react’

const Footer = () => {

      return (

            <div>

<h2>Footer</h2>

</div>

)

}

export default Footer

 

ii.) Create new file profile.jsx under components folder and type rafce which will generate code for basic react component.

 

import React  from ‘react’

const Profile = () => {

      return(

            <div>

            <h2>Profile</h2>

</div>

)

}

export default Profile

ii.) Create new file Contact.jsx under components folder and type rafce which will generate code for basic react component.

import React  from ‘react’

const Contact = () => {

      return(

            <div>

            <h2>Contact</h2>

</div>

)

}

export default Contact

 

iv.) impot component in App.jsx file

import React from ‘react’

import ‘./App.css’

import Profile from ‘./components/Profile’

import Footer from ‘./components/Footer’

function App() {

      return  (

            <>

            <Profile />

            <Footer />

</>

)

}

export default App

V.) Add Contact component inside Profile component.

import React  from ‘react’

const Profile = () => {

      return(

            <div>

            <h2>Profile</h2>

            <Contact />

</div>

)

}

export default Profile

 

VI.) provide phone number in contact and footer component

Contact.jsx

import React  from ‘react’

const Contact = () => {

      return(

            <div>

            <h2>Contact</h2>

            <h3>Phone: </h3>

</div>

)

}

export default Contact

Footer.jsx

import React from ‘react’

const Footer = () => {

      return (

            <div>

<h2>Footer</h2>

<h3>Phone: </h3>

</div>

)

}

export default Footer

 

VII.) useContext is used to consuming context, add AppContext inside useContext.

 

Footer.jsx

 

import React, { useContext } from ‘react’

import { AppContext } from ‘../context/AppContext’

const Footer = () => {

      const {phone, name} = useContext(AppContext)

      return (

            <div>

<h2>Footer</h2>

<h3>Phone: {phone}</h3>

<h3>Name: { name }</h3>

</div>

)

}

export default Footer 

 

Contact.jsx

 

import React, { useContext } from ‘react’

import { AppContext } from ‘../context/AppContext’

 

const Contact = () => {

const {phone, name} = useContext(AppContext)

      return(

            <div>

            <h2>Contact</h2>

            <h3>Phone: {phone}</h3>

<h3>Name: { name }</h3>

</div>

)

}

export default Contact






React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...