skip to Main Content

useRefinmentList is an Algolia hook which accepts a sortBy prop.

The definition of sortBy is type: string[] | (a: FacetValue, b: FacetValue) => number.

If I pass in a sort function I wrap it in a useCallback, otherwise I pass in an array. This violates the rule that hooks can’t be called conditionally. In this case, useCallback is only called if sortBy is a sort function.

My code right now:

useRefinementList({
  attribute: 'my_attribute',
  sortBy: sortBy?.length
    ? sortBy
    : useCallback(
        (a, b) => myCustomSortFunction(a, b, attribute),
        [attribute]
      ),
})

How can I refactor my code to conform to the rule?

2

Answers


  1. Does taking the hook out of the condition work for you?

    const cb = useCallback(
      (a, b) => myCustomSortFunction(a, b, attribute),
      [attribute]
    );
    
    useRefinementList({
      attribute: "my_attribute",
      sortBy: sortBy?.length ? sortBy : cb,
    });
    
    Login or Signup to reply.
  2. You can use useMemo instead of useCallback:

    useRefinementList(useMemo(
      () => ({
        attribute: 'my_attribute',
        sortBy: sortBy?.length
          ? sortBy
          : (a, b) => myCustomSortFunction(a, b, attribute),
      }),
      [sortBy, attribute]
    ))
    

    or

    useRefinementList({
      attribute: 'my_attribute',
      sortBy: useMemo(
        () => sortBy?.length
          ? sortBy
          : (a, b) => myCustomSortFunction(a, b, attribute),
        [sortBy, attribute]
      ),
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search