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

hook #1

Open
lloydzhou opened this issue Mar 10, 2023 · 2 comments
Open

hook #1

lloydzhou opened this issue Mar 10, 2023 · 2 comments

Comments

@lloydzhou
Copy link
Owner

  1. change component like react function component
  2. add useState hook
function Counter(props, { count = 0 }, update) {
  const increment = () => update({ count: ++count });
  return <button onclick={increment}>{count}</button>
}

--> 
function Counter(props) {
  const [count, setCount] = useState(0)
  const increment = () => setCount(count + 1);
  return <button onclick={increment}>{count}</button>
}
@lloydzhou

This comment was marked as off-topic.

@lloydzhou
Copy link
Owner Author

lloydzhou commented Mar 13, 2023

<div id="root" />
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/jsx" data-type="module">
/** @jsx h */
/** @jsxFrag Fragment */

import { h, Fragment, render, useState, useEffect, useRef } from "./little-vdom.js";

function Since({ time }) {
  const [count, setCount] = useState()
  const r = useRef()
  useEffect(() => {
    console.log('update', r.current)
    const timer = setTimeout(() => {
      setCount(count + 1) // update every second
    }, 1000)
    return () => clearTimeout(timer)
  }, [count])
  useEffect(() => {
    console.log('mounted', r, r.current)
    return () => {
      console.log('unmounted')
    }
  }, [])
  const ago = (Date.now() - time) / 1000 | 0;
  return (
    <>
      <h1>Title</h1>
      <time ref={r}>{ago}s ago</time>
    </>
  )
}

function App() {
  const [visible, setVisible] = useState(true)
  useEffect(() => {
    setTimeout(() => setVisible(false), 3000)
  }, [])
  return <div>{visible ? <Since time={Date.now()} /> : <div>clear</div>}</div>
}

render(<App />, document.querySelector('#root'))
</script>

@lloydzhou lloydzhou mentioned this issue Mar 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant