DEV Community

dewelooper
dewelooper

Posted on

prevState in functional components

Hello,
I'm now learning React.js library and yesterday I read about prevState updater mechanism for class component but I cant find nothing about similar mechanism for functional component. Exist something similar or maybe it doesent needed?

Thank you
K.

Top comments (1)

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>
  );
}