2019-03-23

@cshooks/usetrie, A React Hook for Typeahead/Autocomplete

react, javascript, npm, opensource

banner

title: "@cshooks/usetrie, A React Hook for Typeahead/Autocomplete" date: "2019-03-23" banner: ./images/featured-image.jpg published_at: "2019-03-23T19:09:37.000Z" tags: "react, javascript, npm, opensource" author: Sung M. Kim

_Photo byย Jamie Streetย onย _Unsplash - "trie" is from "Retrieval" thus the cute ๐Ÿถ "Retriever"

I've released @cshooks/usetrie.

It's a React Hook for Typeahead/autocompletion.

@cshooks/hooks will be the home ๐Ÿ  of Computer Science data structures/algorithms related hooks.

๐Ÿค” Why?

When you have a list of texts you want to match by prefix, you have to match each text in an array one by one, which can be time consuming.

Trie is a data structure, which stores text in a tree, which enables a fast prefix look up.
And useTrie works as a facade to enable fast prefix search.

๐Ÿ”ง How?

Check out the README file, which explains the usage in detail.

Here are some quick demo Sandboxes for the impatients.

Demos

โž• Additional Info

I've created this initially for academic purposes to learn Trie data structure so Trie class is imperative and useTrie hook was forced to fit to work with declarative nature of React as shown below, which is not ideal.

function reducer(state: ReducerState, action: TrieAction): ReducerState {
switch (action.type) {
case 'ADD':
state.trie.add(action.word);
return { ...state, trie: state.trie };
case 'REMOVE':
state.trie.remove(action.word as string);
return { ...state, trie: state.trie };
default:
return state;
}
}
function useTrie(
initialWords: Words,
isCaseInsensitive = true,
getText: (obj: any) => string = obj => obj
): ITrie {
const trie = new Trie(initialWords, isCaseInsensitive, getText);
const [state, dispatch] = React.useReducer(reducer, { trie, word: '' });
function add(word: Word): void {
dispatch({ type: 'ADD', trie, word });
}
function remove(word: string): void {
dispatch({ type: 'REMOVE', trie, word });
}
return { ...state.trie, add, remove };
}
view raw useTrie.jsx hosted with โค by GitHub

add/remove returns a new instance

https://github.com/cshooks/hooks/blob/master/packages/useTrie/src/index.ts#L191

I'd really appreciate any feedback on how I can improve the code base.

I will share in the next post what I've learned and failures.

And I plan to add other hooks returning Min/Max heaps & Permutations.

๐Ÿ” Resources