2. Use Lifecycle
Lifecycle Hooks are provided for the first argument of the function.
created
is equivalent to calling a function.mounted
=>onMounted
init
=>onInit
destroy
=>onDestroy
onInit
(or onMounted
) and onDestroy
must match. If it is registered in onInit
, it must be released in onDestroy
.
In Strict Mode development environment of React 18 will occur in the order.
created
=>created
mounted
=>init
destroy
mounted
=>init
If you don't return an instance in the created
lifecycle, you should return an instance in mounted
.
And you have to tell it the initial value of the state via the setInitialState
function.
import { reactive } from "@cfcs/core";
const REACTIVE_ADAPTER = ({ setInitialState, onMounted }) => {
setInitialState({
width: 0,
height: 0,
});
onMounted(() => {
const obj = reactive({
width: 0,
height: 0,
});
return obj;
});
The following code changes the width
and height
state to 100 after 1 second.
import { reactive } from "@cfcs/core";
const REACTIVE_ADAPTER = ({ onInit, onDestroy }) => {
const obj = reactive({
width: 0,
height: 0,
});
let timerId = 0;
onInit(() => {
// enable timer
timerId = setTimeout(() => {
obj.width = 100;
obj.height = 100;
}, 1000);
});
onDestroy(() => {
// disable timer
clearTimeout(timerId);
});
return obj;
};
Frameworks
- React
- Vue@2
- Vue@3
- Svelte
import { useReactive } from "@cfcs/react";
export function App() {
const {
width,
height,
} = useReactive(REACTIVE_ADAPTER);
return <div>{width}x{height}</div>;
}