Spooky Ghost pion Docs Toggle darkmode

Hooks: useCallback

Very similar to useMemo but instead of writing a function that returns your memoized value, your function is the memoized value. This and useMemo are often overused so try to only use this when your callback has dependencies and it is itself a dependency for something else (like useEffect) .

import { component, html, useCallback, useState, useEffect } from '@pionjs/pion';

const input = setter => e => setter(e.target.value);

customElements.define('use-callback', component(function Counter(element) {
  const [email, setEmail] = useState('');
  const [pword, setPword] = useState('');
  const [response, setResponse] = useState('');

  const submit = useCallback(async event => {
    event.preventDefault();
    api.post('submit', { email, pword })
      .then(r => r.text())
      .then(x => setResponse(x));
  }, [email, pword]);

  useEffect(() => {
    element.shadowRoot.addEventListener('submit', submit);
    return () => element.shadowRoot.removeEventListener('submit', submit);
  }, [submit]);

  return html`
    <form>
      <label> Email
        <input type="email"
            .value=${email}
            @input=${input(setEmail)}
            required /> </label>
      <label> Password
        <input type="password"
            .value=${pword}
            @input=${input(setPword)}
            required /> </label>
      <button type="submit">Submit</button>
      <output>${response}</output>
    </form>
  `;
}));

API

useCallback

Parameters

fn

T

callback to memoize

inputs

unknown[]

dependencies to callback memoization

Returns

T

Exports

import { useCallback } from '@pionjs/pion/lib/use-callback';