useState Hook

Learn how the “useState” hook in functional components can replace “this.setState” functionality for a React class component. This lesson will examine its syntax, usage, and it will also provide examples.

What is it?

Start by looking at how the state is managed by using a class.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: []
    };
  }
  
  setItems = items => {
    this.setState(items);
  }
  
  render() {
    // some code here
  }
}

Here this.state is being used to initialize items and this.setState is used to update the state.

With useState hook, replace this.state and this.setState with a single hook call. The above example will reflect this when using the useState hook to manage items.

 ...