DEV Community

Huy Nguyen
Huy Nguyen

Posted on

setState in Functional component

When you use Functional Component to develop your ReactJS application. Sometime, you need to use state in your component, and it maybe cause somethings like this:

const [error, setError] = useState<string | undefined>(undefined);
const [value, setValue] = useState<Record<string, any>>({});
// and n lines to declare states...
Enter fullscreen mode Exit fullscreen mode

Basic

So, to reduce these lines, I recommend you should use another solution to declare states for your component. That is useReducer :)

And this is my solution when use it in my component:

type tComponentState = {
  error: string | undefined;
  value: Record<string, any>;
  // ...n state's type
}

const [state, setState] = useReducer((
  prev: tComponentState,
  after: Partial<tComponentState>,
) => ({ ...prev, ...after }), {
  error: undefined,
  value: {},
});

// update new value for any state
setState({ value: { field: '123' }});
// or update n states together
setState({
  value: { field: '456' },
  error: 'Invalid format',
});
Enter fullscreen mode Exit fullscreen mode

And now, your code will easier to read, or maintenance, or add some states :)

High level

Yep, sometimes, you will need to verify your data before update your state, and now, you can do it inside your useReducer, like this:

const [state, setState] = useReducer((
  prev: tComponentState,
  after: Partial<tComponentState>,
) => {
  const stateNeedUpdate = { ...prev, ...after };
  if (!value || !value.field || Number.isNaN(value.field)) {
    stateNeedUpdate.value.field = '';
  }
  return stateNeedUpdate;
}, {
  error: undefined,
  value: {},
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)