YGNCodeAI နှင့်နည်းပညာအမေးအဖြေ

မှတ်ချက်။ AI ပြောတိုင်းအမှန်မဟုတ်ပါဘူး၊ တခါတလေသူကအမှားတွေပါပြောတက်ပါတယ်။ ကိုယ်ပိုင်စဥ်းစားဆင်ခြင်ဆုံးဖြတ်ပါ။

Saw Zarni Lin Htay 18 Sep 2024, 2:48 am

React ကို clean code အနေနဲ့ ဘယ်လိုရေးသင့်လဲ နမူနာ အနေနဲပြပေးပါ။

React မှာ clean code ရေးဖို့အတွက် အောက်ပါအချက်တွေကို လိုက်နာသင့်ပါတယ်။ နမူနာအနေနဲ့ ပြပေးပါမယ်။

  1. Component တွေကို သေးသေးလေးတွေခွဲရေးပါ။
// Bad
function UserProfile() {
  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: John Doe</p>
      <p>Email: [email protected]</p>
      <h2>Posts</h2>
      <ul>
        <li>Post 1</li>
        <li>Post 2</li>
      </ul>
    </div>
  );
}

// Good
function UserInfo({ name, email }) {
  return (
    <>
      <h1>User Profile</h1>
      <p>Name: {name}</p>
      <p>Email: {email}</p>
    </>
  );
}

function UserPosts({ posts }) {
  return (
    <>
      <h2>Posts</h2>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </>
  );
}

function UserProfile() {
  return (
    <div>
      <UserInfo name="John Doe" email="[email protected]" />
      <UserPosts posts={[{ id: 1, title: 'Post 1' }, { id: 2, title: 'Post 2' }]} />
    </div>
  );
}
  1. Destructuring သုံးပါ။
// Bad
function UserInfo(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}

// Good
function UserInfo({ name, age }) {
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
}
  1. Conditional Rendering ကို အရှင်းဆုံးနည်းနဲ့ရေးပါ။
// Bad
function Welcome({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign in.</h1>;
  }
}

// Good
function Welcome({ isLoggedIn }) {
  return <h1>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</h1>;
}
  1. Custom Hooks သုံးပြီး logic တွေကို ခွဲထုတ်ပါ။
// Custom Hook
function useUserData(userId) {
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    fetchUserData(userId).then(setUserData);
  }, [userId]);

  return userData;
}

// Component
function UserProfile({ userId }) {
  const userData = useUserData(userId);

  if (!userData) return <div>Loading...</div>;

  return (
    <div>
      <h1>{userData.name}</h1>
      <p>{userData.email}</p>
    </div>
  );
}

ဒီနမူနာတွေက React မှာ clean code ရေးဖို့အတွက် အခြေခံကျတဲ့ နည်းလမ်းတွေပဲ ဖြစ်ပါတယ်။

ပြန်လည်မျှဝေပါ... Facebook Twitter LinkedIn WhatsApp Telegram