Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

The useState hook is one of them. Let’s go through this hook ❤️.

The useState

If you are following the functional-based component approach then This is the hook that you must be using a lot.

The useState hook has been introduced to handle the state inside the functional component. Prior to the hooks, we could not have managed the state inside functional components. They just used to be a Dumped or Presentational Components.

useState is a Hook. We call it inside a function component to add some local state to it. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together.

React components automatically re-render whenever there is a change in their state

Let’s have a look at an example

Tips 💁

If your state depends on the previous state update the state as follows

  • If case like counter
setCount((previousCount) => previousCount + 1);


  • If Object
setState((previousState) => ({ ...previousState, key: "some updates" }));


  • If Array
setState((previousState) => ([ ...previousState, ...newArray ]));


Happy Coding 😊…