DEV Community

Discussion on: prevState in functional components

Collapse
 
kewah profile image
Antoine Lehurt

Pre hooks, functional components didn't have a state. You can only pass props to the component and it will return an element. So, it's not needed to handle prevState in functional components.

function MyComponent(props) {
  return (
    <div>{props.children}</div>
  )
}

However using hooks, prevState is the current value of the state (using useState).

For instance, using prevState in a Class component to reset the count when we reach 10

class Example extends React.Component {
  handleClick = () => {
    this.setState(prevState => {
      if (prevState.count === 10) {
        return {
          count: 0
        }
      }

      return {
        count: prevState.count + 1
      }
     });
  };

  render() {
    return <button onClick={this.handleClick}>{this.state.count}</button>;
  }
}

Using hooks:

function Example() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    if (count === 10) {
      setCount(0)
    } else {
      setCount(count + 1)
    }
  }

  return (
    <button onClick={handleClick}>{count}</button>
  );
}