Hydration
Hydration is the process of attaching event handlers to html
on the client side but in $render, Hydration
works by default in the browser so there is no need to take some extra time to re-compile
. What you write is what you get in the browser.
When you wrap a function with template literals while passing it to an event handler in a component, it is hydrated into the component.
Note: It is recommended to create any utility with a native function.
function add(props) {
const result = props.first + props.second;
$render(Calculator, result);
}
function Calculator(result) {
return `
<div id="calc">
${result ? `updated to ${result}` : ""}
<button
onClick="$trigger(${add}, null, {first:4, second:5})">
add
</button>
</div>
`;
}
The browser will hydrate the add
function above into the Calculator
component. It attaches the function to the element returned by the Calculator
component.
<button
onClick="$trigger(function add(props){
return props.first + props.second;
}, {first:4, second:5})">
add
</button>
Note: You don't need to wrap a function in template literals (${toggle}
) while working with a script tags because all functions are accessible in a script
tag by default. You only need it in esModules.
Avoiding hydrations from template literals
Maybe you don't like how hydrated functions look in the browser, you can avoid hydration by using the $utils()
method provided by $render to use function
utilities globally in any component.