React: Newly Launched useTransition hooks.

React: Newly Launched useTransition hooks.

Hi there,

Here are below snippet shows how to execute the useTransition hook in React.


mport React, { useState, useTransition } from 'react';

const MyComponent = () => {
? const [showContent, setShowContent] = useState(false);
? const [startTransition, isPending] = useTransition({ timeoutMs: 300 });

? const handleClick = () => {
? ? startTransition(() => {
? ? ? setShowContent(!showContent);
? ? });
? };

? return (
? ? <div>
? ? ? <button onClick={handleClick} disabled={isPending}>
? ? ? ? {showContent ? 'Hide Content' : 'Show Content'}
? ? ? </button>

? ? ? {isPending ? (
? ? ? ? <div
? ? ? ? ? style={{
? ? ? ? ? ? width: '100px',
? ? ? ? ? ? height: '100px',
? ? ? ? ? ? backgroundColor: showContent ? 'red' : 'green',
? ? ? ? ? ? transition: 'background-color 0.3s ease-in-out',
? ? ? ? ? }}
? ? ? ? />
? ? ? ) : null}


? ? ? {showContent && <div>This is the content to show or hide.</div>}


? ? ? {!isPending && (
? ? ? ? <button onClick={handleClick} disabled={isPending}>
? ? ? ? ? {showContent ? 'Hide Content' : 'Show Content'}
? ? ? ? </button>
? ? ? )}
? ? </div>
? );
};

export default MyComponent;
        

Brief Explanation: -

  1. When the button is clicked, the handleClick function is called, which triggers the transition using startTransition. Inside the transition callback, the showContent state is toggled.
  2. The isPending variable is used to determine if a transition is in progress. While the transition is ongoing, the button that triggered the transition is disabled using the isPending value as the disabled attribute. This prevents users from triggering the transition multiple times.
  3. Once the transition is completed and isPending becomes false, both buttons are rendered again, allowing the user to show or hide the content by clicking either button.
  4. The colored transition effect remains the same as in the previous example, with the background color changing based on the showContent state.


Thanks for reading the post, and looking forward to your valuable insight. We are actively seeking B2B partnership opportunities. If you are interested in collaborating or exploring, please feel free to contact me at [email protected] or DM me. Let's connect together and explore potential growth.

Purvak Pathak MBA MCP

要查看或添加评论,请登录

Parth Bhoot的更多文章

社区洞察

其他会员也浏览了