React Hooks Cheat Sheet

Bunlong

Bunlong

React Patterns Team

React Hooks Cheat Sheet

State Management#

useState()#

Declare state.

const [name, setName] = useState('Initial value');

Update state.

setName('New value'); // directly
setName((value) => 'New' + value); // based on previous state

What is React Server Component

Bunlong

Bunlong

React Patterns Team

What is React Server Component?

What is React Server Component?#

React Server Component (CSR) is a new component in React.

Recently, All components in React are client-side component (MyComponent.js) but now you can create them as server-side component by just adding .server (MyComponent.server.js).

Anyway client-size component and server-size component work together very well.

How to use async function in useEffect hook?

Bunlong

Bunlong

React Patterns Team

How to use async function in useEffect hook?

How to use async function in useEffect hook?#

At first glance you will have an idea as following.

useEffect(async () => {
await someTask();
}, []);

What's wrong?

The compiler should be yielding something as following.

Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'.

Optimize Your Promise by Using Async/Await in React

Bunlong

Bunlong

React Patterns Team

Optimize Your Promise by Using Async/Await in React

When Promise was introduced in ES5, it was meant to solve a problem with asynchronous code, and they did, but over the 2 years that separated ES5 and ES7, it was clear that promises could not be the final solution.

Promise was introduced to solve the famous callback hell problem, but they introduced complexity on their own, and syntax complexity.

How can we escape Promise syntax complexity? Good things come to those who Await.

When to useMemo and useCallback?

Bunlong

Bunlong

React Patterns Team

When to useMemo and useCallback?

React library provides us two built-in hooks to optimize the performance of our applications are useMemo and useCallback.

The usage of this two built-in hooks is quite similar so it can get confusing about when to use each. To clear that confusion, let's dig in and understand the actual difference and the correct way to use them both.