Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fun useRef #89

Open
reboottime opened this issue May 10, 2024 · 0 comments
Open

Fun useRef #89

reboottime opened this issue May 10, 2024 · 0 comments

Comments

@reboottime
Copy link
Owner

reboottime commented May 10, 2024

For Fun

For code bellow

import { useEffect, useRef } from 'react';


export default function App() {
  return (
    <>
      <UserExample />
      <UserExample />
    </>
  );
}

const UserExample = () => {
  const user = useUser('kate');

  return <div>{user?.name ?? 'kate'}</div>;
};

const useUser = (name: string) => {
  const userRef = useRef<User | null>(null);

  useEffect(() => {
    let user = userRef.current;
    if (!user) {
      userRef.current = new User(name);
      user = userRef.current;
    }
  }, [name]);

  return userRef.current;
};

class User {
  name: string;
  constructor(name: string) {
    this.name = name;
    console.info('initialize user instance');
  }
}

How many User instance was intiated?

  • A0: 0
  • A1: 1
  • A2: 2

(:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant