Skip to content

[hooks] useState - "setState" callback #98

Closed
@marcellomontemagno

Description

@marcellomontemagno

Hi, I'm very hyped about the hooks api and I started experimenting with it on some small side project.

I've noticed that the "setState" function returned by the useState hook doesn't have an "afterRender" callback (the second argument of this.setState in classes)

I didn't find further informations about this in the doc. Is there any design reason why the "afterRender" callback is not present? Is there a plan to introduce it later on?

The reason I ask is that during the past years of react usage I found a few scenarios (very rarely though) were not having the "afterRender" callback would result in a quite tedious implementation of componentDidUpdate or pushed me to change the shape of my state to work around it (I can provide examples about this)

In the meanwhile here the snippet I used to understand that no "afterRender" callback is used by the "setState" of hooks

Counter.js

import React, {useState} from 'react';

export const defaultState = {count: 0}

export const useCounter = () => {

  const [state, setState] = useState(defaultState)

  return {
    ...state,
    onIncreaseCounter () {
      setState({...state, count: state.count + 1}, () => {console.log('++++++++++++++++++')})
    },
    onDecreaseCounter () {
      setState({...state, count: state.count - 1}, () => {console.log('++++++++++++++++++')})
    }
  }

}

export default function Counter ({count, onIncreaseCounter, onDecreaseCounter}) {
  return <div>
    {count}
    <button onClick={onIncreaseCounter}>+</button>
    <button onClick={onDecreaseCounter}>-</button>
  </div>
}

Root.js

import React from 'react';

import Counter, {useCounter} from "./Counter";

export default function Root () {
  return <Counter {...useCounter()}/>
}

the log never appears in the console after after increasing and decreasing the counter

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions