synchronous and an asynchronous component in React?

Started 10 months ago by Manny in React JS

difference between a synchronous and an asynchronous component in React?

Body

difference between a synchronous and an asynchronous component in React?

1 Replies

  • Replied 10 months ago

    Report

    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;