×

React Js

The World's best Software Development Study Portal

UseCallbackAPI Example

UseCallbackAPI with Examples

With the help of UseCallbackAPI you will tell react to remember the function you passed after rendering the compoment. UseCallbackAPI will call itself whenever you load the page.

UseCallbackAPI

App.js

import React from 'react'; import Parent from './Parent'; function App(){ return( <div> <Parent/> </div> ) } export default App; --------------------------------------------------------

Parent.js

import React,{ useCallback, useState } from 'react' import Child from './Child'; function Parent() { const[countone, setCountone]= useState(0); const[counttwo, setCounttwo]= useState(0); const getItems = useCallback((num) =>{ //this is business logic// (logic as depend on count two) console.log(counttwo+num,counttwo-num) for(let i=0;i<1000000000;i++){} //start loop// console.log('getItems') return[counttwo+1,counttwo-1] },[counttwo,countone]) return ( <div> <button onClick={()=>setCountone(countone+1)}>Count One: {countone}</button> <button onClick={()=>setCounttwo(counttwo+1)}>Count Two: {counttwo}</button> <Child getItems={getItems}/> {/*child passes as a props*/} </div> ) } export default Parent; ----------------------------------------------------------

Child.js

import React, { useEffect, useState } from 'react' function Child({getItems}) { const[items, setItems] =useState([]) useEffect(()=>{ setItems(getItems) // when set as no update// },[getItems]) return ( <div> {items && items.map(item=>{ <div key={item}>{item}</div> })} </div> ) } export default Child;