5 ways that will change how you write React hooks

adamklein

adam klein

Posted on April 25, 2020

5 ways that will change how you write React hooks

NOTE!

Tips and methods in this post are my own personal preference, and I'm sure many people will disagree.

There is no right or wrong. Every approach has its pros and cons. If you take just one good thing out of the post - I've done my share.

I do not mean to insult anyone who thinks differently. Some of the "bad code" examples used to be code that I've written myself!

If you do think differently - you are more then welcome to comment and change my mind.

Good reading!

1. An effect has no name

Writing several effects in the same component?

const MyComp = () => {
  useEffect(() => {
    ...
  });
  useEffect(() => {
    ...
  });
  useEffect(() => {
    ...
  });
}

I don't want to read your code just to know what they are doing... duh...

Here's a tip for you, use named functions:

const MyComp = () => {
  useEffect(function fetchData() {
    ...
  });
  useEffect(function subscribeToUpdates() {
    ...
  });
  useEffect(function useInterval() {
    ...
  });
}

Much better right?

There's another benefit - you will see the effect name in React dev tools:
Alt Text

Don't be a smarty pants and try to extract to constants, like this:

const MyComp = () => {
  function fetchData() {...}
  function subscribeToUpdates() {...}
  function useInterval() {...}

  useEffect(fetchData);
  useEffect(subscribeToUpdates);
  useEffect(useInterval);
}

Because then you are only fooling the linter, not me!
(Exhaustive deps rules won't work for the function implementations)

2. async functions

Effects don't support async functions (you can't return a promise).
It's so annoying, let's try to solve it:

const MyComp = () => {
  useEffect(() => {(async() => {
    ...
  })();});
}

WTF?! IIFE?! Are we in 2010?!
Try again please:

const MyComp = () => {
  async function fetchData() {...}
  useEffect(() => {
    fetchData();
  });
}

No! You are not listening! (See comment above about exhaustive deps)

OK, I'll give it to you:

const MyComp = () => {
  useEffect(function doSomething() {
    async function doSomethingAsync() {
    }
    doSomethingAsync();
  });
}

Sometimes you just gotta be verbose with them code.

Or, if you insist on taking the function out, take it out completely from the component and pass it the deps:

async function doSomethingAsync(dep1, dep2) {
  ...
}

const MyComp = () => {
  useEffect(function doSomething() {
    doSomethingAsync(dep1, dep2);
  }, [dep1, dep2]);
}

3. Debouncing the hooks way

It's really stupid to implement your own debounce when there is a ton of libraries out there who already have. Right?!

Wrong! 'Cause now we got hooks!!

const MyComp = () => {
  useEffect(function doSomethingDebounced() {
    const timeout = setTimeout(() => {
      doSomethingWith(value);
    }, 500);
    return () => clearTimeout(timeout);
  }, [value]);
}

Ummm.... what?
Yes, that is an implementation of debounce with nothing but effect, timeout and cleanup function. You're smart, think about it.

4. useCallbacks? Nahhh....

You might think that useReducer is better than useState when managing a complex object:

function reducer(state, action) {
  switch(action.type) {
    case 'MOVE_RIGHT':
      return { ...state, left: state.left + action.step };
    case 'MOVE_DOWN':
      return { ...state, top: state.top + action.step };
    default:
      return state;
  }
}
const [position, dispatch] = useReducer(reducer, { left: 0, top: 0 });

But think about it, you will still have to use useCallback for each action dispatch if you want a stable ref:

const moveRight = useCallback((step) => dispatch({ type: 'MOVE_RIGHT', step }), []);

Think about this version instead:

const [position, setPosition] = useState({ left: 0, top: 0 });
const actions = useMemo(() => ({
  moveRight: step => {
    setPosition(state => ({ ...state, left: state.left + step }))
  },
  moveDown: step => {
    setPosition(state => ({ ...state, top: state.top + step }))
  }
}), []);

All actions are memoized!
And no switch case, meaning better debugging experience and TypeScript integration.

5. Use useContext with selectors to bail out of render

You've probably heard many times that it's impossible to bail out of rendering if you're using Context.

Well.....

You're right. I'll give it to you.

But cross your fingers, 'cause selectors are coming to a version near you:

https://github.com/reactjs/rfcs/pull/119

When this is accepted, we would be able to do this:

useContext(MyContext, value => value.someProperty);

Hopefully in the next few months, but who knows, right?!

Hope you learned something new! Tell your friends.

💖 💪 🙅 🚩
adamklein
adam klein

Posted on April 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related