Skip to main content

Derived State

––– views

Go to Twitter Post

useState Might Be Overused

useState sometimes is overused, there will be a case where you can just use Derived State

Derived

The wrong way

Say that we're building this simple component

Derived

Natural way is to create another state for filtered since it's a data that can change

Derived

React Re-renders

However, react re-renders! Every time the search & data state changes, it's going to call the whole function again.

Derived

Derived State

Every re-render, if you have a computation, it's going to be re-run again and again. So we can derive the filtered from the data & search state itself.

This concept is called derived state.

Derived

Performance improvement

If you're concerned with performance, you can utilize useMemo hook, so every re-render it can check the dependency array and decide if it should recompute

Derived