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

No comments:

Post a Comment

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 ...