You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// useState - Manage component statefunctionCounter(){// State declaration: [value, setValue]const[count,setCount]=useState(0);return(<buttononClick={()=>setCount(count+1)}>
Count: {count}</button>);}// useEffect - Handle side effectsfunctionUserStatus({ id }){const[isOnline,setIsOnline]=useState(false);useEffect(()=>{// Runs on mount and when id changescheckUserStatus(id);return()=>{// Cleanup function runs before next effectcleanupStatusCheck(id);};},[id]);// Dependency arrayreturn<div>User is: {isOnline ? 'Online' : 'Offline'}</div>;}// useRef - Persist values between rendersfunctionTextInput(){// Create a ref to store DOM elementconstinputRef=useRef(null);constfocusInput=()=>{inputRef.current.focus();};return(<><inputref={inputRef}/><buttononClick={focusInput}>Focus Input</button></>);}
Component Lifecycle
// Modern lifecycle using hooksfunctionLifecycleDemo(){// Component MountuseEffect(()=>{console.log('Component mounted');// Component Unmountreturn()=>{console.log('Component will unmount');};},[]);// Empty array = run once on mount// Component UpdateuseEffect(()=>{console.log('Data updated');},[/* dependencies */]);return<div>Lifecycle Demo</div>;}// Error BoundaryclassErrorBoundaryextendsReact.Component{state={hasError: false};staticgetDerivedStateFromError(error){return{hasError: true};}componentDidCatch(error,info){console.log('Error caught:',error,info);}render(){if(this.state.hasError){return<h1>Something went wrong.</h1>;}returnthis.props.children;}}
Context API
// Create context for global stateconstThemeContext=React.createContext('light');// Provider componentfunctionThemeProvider({ children }){const[theme,setTheme]=useState('light');return(<ThemeContext.Providervalue={{ theme, setTheme }}>{children}</ThemeContext.Provider>);}// Consumer component using useContextfunctionThemedButton(){const{ theme, setTheme }=useContext(ThemeContext);return(<buttononClick={()=>setTheme(theme==='light' ? 'dark' : 'light')}>
Current theme: {theme}</button>);}// UsagefunctionApp(){return(<ThemeProvider><ThemedButton/></ThemeProvider>);}
Routing
// Basic routing setup using react-router-domimport{BrowserRouter,Routes,Route,Link}from'react-router-dom';// Navigation componentfunctionNavigation(){return(<nav><Linkto="/">Home</Link><Linkto="/about">About</Link><Linkto="/users">Users</Link></nav>);}// Route setupfunctionApp(){return(<BrowserRouter><Navigation/><Routes><Routepath="/"element={<Home/>}/><Routepath="/about"element={<About/>}/><Routepath="/users/:id"element={<UserProfile/>}/></Routes></BrowserRouter>);}// Route with parametersfunctionUserProfile(){// Get route parametersconst{ id }=useParams();return<div>User Profile: {id}</div>;}
Data Fetching
// Fetch data with useEffectfunctionUserList(){const[users,setUsers]=useState([]);const[loading,setLoading]=useState(true);useEffect(()=>{// Fetch users when component mountsconstfetchUsers=async()=>{try{constresponse=awaitfetch('https://api.example.com/users');constdata=awaitresponse.json();setUsers(data);}catch(error){console.error('Error fetching users:',error);}finally{setLoading(false);}};fetchUsers();},[]);if(loading)return<div>Loading...</div>;return(<ul>{users.map(user=>(<likey={user.id}>{user.name}</li>))}</ul>);}// Custom fetch hookfunctionuseDataFetching(url){const[data,setData]=useState(null);const[loading,setLoading]=useState(true);const[error,setError]=useState(null);useEffect(()=>{constfetchData=async()=>{try{constresponse=awaitfetch(url);constresult=awaitresponse.json();setData(result);}catch(err){setError(err);}finally{setLoading(false);}};fetchData();},[url]);return{ data, loading, error };}// Usage of custom hookfunctionUserData({ userId }){const{ data, loading, error }=useDataFetching(`https://api.example.com/users/${userId}`);if(loading)return<div>Loading...</div>;if(error)return<div>Error: {error.message}</div>;return<div>User: {data.name}</div>;}