Why ref is not working in vue3 jsx functional components?

879 Views Asked by At

As shown in the following code, it's not working. If I put the code on (1) outside of the function, it works. Why? Or any solutions?

// vue3.2 jsx functinal components

import { ref } from 'vue'

// const count = ref(0) // (2) it works here

export default function Counter() {
  const count = ref(0) // (1) not working here
  return (
    <>
      <div>count: {count.value}</div>
      <button
        onClick={() => {
          count.value++
        }}
      >
        add
      </button>
    </>
  )
}
2

There are 2 best solutions below

1
On BEST ANSWER

You can change a little,use defineComponent wrapper Counter.

refer: Composition API in a functional component

import { ref } from 'vue'

// const count = ref(0) // (2) it works here

function Counter() {
  const count = ref(0) // (1) not working here
  return () => (
    <>
      <div>count: {count.value}</div>
      <button
        onClick={() => {
          count.value++
        }}
      >
        add
      </button>
    </>
  )
}

export default defineComponent(Counter);
0
On

This is how Functional Components work - the function is called every time the component is rendered. Which means the new count ref is created each time a component is rendered (it is a local variable)

Functional components are an alternative form of component that don't have any state of their own.

There is no solution for that. If you need local state, do not use functional component.

Moving ref creation to module scope (2) is not solution either as it will lead to a single counter shared between all usages of your component