difference between a synchronous and an asynchronous component in React?
Body
difference between a synchronous and an asynchronous component in React?
Tags: synchronous, asynchronous, react component, solutions
1 Replies
-
synchronous component:
import React, { useState } from 'react'; const SynchronousComponent = () => { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); }; return ( <div> <p>Count: {count}</p> <button onClick={handleClick}>Increment</button> </div> ); }; export default SynchronousComponent;
Asynchronous Component:
import React, { useState, useEffect } from 'react'; const AsynchronousComponent = () => { const [data, setData] = useState(null); useEffect(() => { // Simulating an asynchronous operation (e.g., fetching data) setTimeout(() => { setData('Fetched data'); }, 1000); }, []); // Empty dependency array ensures useEffect runs once return ( <div> <p>Data: {data}</p> </div> ); }; export default AsynchronousComponent;