DEV Community

Discussion on: Don't over useState

Collapse
 
nas5w profile image
Nick Scialli (he/him)

Whenever a state setter function is only used synchronously in an effect, get rid of the state!

That's really interesting and I think it holds up.

One common pattern for derived state is the selector pattern. Your selector is a function of state that returns your derived state value. This pattern is especially helpful for reuse.

// Defined in a shared file/location
const getFullName = state => state.firstName + " " + state.lastName;

// Used in a component
const fullName = getFullName(state);
Enter fullscreen mode Exit fullscreen mode

If the app is large or complex enough, it becomes worth it to bring in a library like reselect to memoize selector return values.

Collapse
 
tkdodo profile image
Dominik D

reselect works well if you need to select things from „outside“ of react, like a redux store. If you are working with hooks based libraries, I prefer writing custom hooks and doing useMemo, which is pretty much the same.