CodeBlanks Logo Icon CodeBlanks

Reading state

Learn to read state from a Zustand store.

Reading state

To read state from a Zustand store you call the returned hook. There are two common methods: take the whole store (const { count, increment } = useCounter()) or select only one field (const count = useCounter((s) => s.count)).

The second method is more performant. Because the component re-renders only when count changes; even if increment reference does not change it does not trigger this render. This pattern is Zustand's recommended selector usage and reduces unnecessary renders.

Writing a selector

A selector is a callback; like (s) => s.count. This callback takes the store state and returns the wanted field. The component re-renders only when this field changes. To select multiple fields you can return an object with helpers like useShallow.

Example: const name = useUser((s) => s.name). Here name carries the user's name. Even if s.email or s.id change, as long as name stays the same no render is triggered. This fine selection makes a difference in large lists and forms.

Practice Read the count value

Complete the CounterValue component. Import useCounter from ./useCounter. Read the value with const count = useCounter((s) => s.count). Return <Text>{count}</Text>.

Starter code

App.js
import React from 'react';
import { Text } from 'react-native';

export function CounterValue() {
  // read count with a selector and show inside Text

  return null;
}

Sample solution

App.js
import React from 'react';
import { Text } from 'react-native';
import { useCounter } from './useCounter';

export function CounterValue() {
  const count = useCounter((s) => s.count);

  return <Text>{count}</Text>;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which usage is more efficient?

  • useCounter((s) => s.count)
  • useCounter.all()
  • useCounter() Correct answer
  • useCounter.read()

Explanation: The selector usage re-renders only when the relevant field changes.

2 Match the reading parts

Term Meaning
useCounter Store hook
(s) => s.count Selector
count Selected value
re-render Happens on value change

3 Write the selector function

Question
const count = useCounter((s) => s.____);
Answer
const count = useCounter((s) => s.count);

Explanation: The count field is selected.

All lessons in Advanced