DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Tatu Tamminen
Tatu Tamminen

Posted on

React custom hook question

I have been implementing a React custom hook. In the project, I noticed a pattern when getting data to the React components.

  • first, we check do we have data already in the store (selector in the function will give the data)
  • if not, we dispatch an action that will have a token and parameters

As it is a crucial part of the app, I thought someone with hook experience might have a look at this.

Especially, the payload and action part. Should I use usePrevious hook and use isEqual from lodash. Or, useMemo?.

All ideas appreciated, thanks!

/* annotated version of the hook */

export function useFetchIfNeeded<T>(
  selector: (state: AppState) => T,
  action: (payload: any) => ThunkAction<any, any, any, any>,
  payload: Object,
  checkFn?: (input: T) => boolean
) {
  // redux hook
  const dispatch = useDispatch()

  // get token
  const token = useSelector((state: AppState) => state.global.token)

  // get data using the selector function
  const data = useSelector(selector)

  // use check function to verify do we need to fetch data or not
  // default is null comparison
  const check = useCallback(() => (checkFn ? checkFn(data) : data !== null), [
    checkFn,
    data
  ])
  const fetch = useCallback(() => {
    if (!token) {
      return
    }

    if (check()) {
      return
    }

    dispatch(
      action({
        ...payload,
        token
      })
    )
    // TODO: action and payload are objects, should I make my own comparison?
  }, [dispatch, token, check, action, payload])
  useEffect(() => {
    fetch()
  }, [fetch])

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!