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)