Skip to main content

Posts

Showing posts from December, 2020

part3 useEffect , conditionally run useEffect

import React, { useState, useEffect } from 'react'; import './App.css' const App = () => { const [cnt, setCnt] = useState(0) const [tmp, setTmp] = useState('10') useEffect(() => { document.title = `${cnt}` console.log("use effect called") },[cnt]) // only run useEffect when cnt value changes, condition applied on cnt return ( <div className="App"> <input type="text" onChange={(e) => { setTmp(e.target.value) console.log(e.target.value) }} /> "text {tmp} " <button onClick={() => setCnt(cnt + 1)}>Plus+</button> {cnt} </div> ); } export default App; //useEffect runs after every render of component sideeffect => any thing that reaches outside of component to do something eg . n / w request manual dom manipulation to modify other parts of dom event Listener , timeout and interval

part 2 react hooks with objects and array

i mport React, { useState } from 'react'; import './App.css' const App = () => { const [name, setName] = useState({ fname: '', lname: '' }) return ( <div className="App"> <form> <input type="text" value={name.fname} onChange= {(e) => setName((prevstate) => ({ ...prevstate, fname: e.target.value }))} /> Fname is {name.fname} <br /> <input type="text" value={name.lname} onChange= {(e) => setName((prevstate) => ({ ...prevstate, lname: e.target.value }))} /> Lname is {name.lname} </form> { JSON . stringify ( name ) } </div> ); } export default App; onChange= {(e) => setName((prevstate) => ({ ...prevstate, lname: e.target.value }))} the ...prevstate above will merge current state to previous state #working with ARRAY import React , { useState } from 'react' ; import './App.css' const App = () => { const [ items , setItems ] =...

react hooks part 1

. import React , { useState } from 'react' ; import './App.css' const App = () => { const [ count1 , setCount1 ] = useState ( 1 ) const [ count2 , setCount2 ] = useState ( 2 ) const [{ count3 , count4 }, setCount ] = useState ({ count3 : 8 , count4 : 9 }) return ( <div className = "App" > <button onClick = { () => { setCount1 ( c => c + 1 ) setCount2 ( c => c + 1 ) } } > Add-it </button> <div> count1= { count1 } </div> <div> count2= { count2 } </div> <button onClick = { () => { setCount (( c ) => ({ ... c , count3 : count3 + 100 , count4 : count4 + 100 }) ) //here "c" is currentstate and the ...c spreadoperator } } > add obj </button> <div> count3= { count3 } </div><div> count4= { count4 } </div> </div> ); } export def...