News for hackers. Stuff that matters.
Re:Thinking in React Hooks by istoica on Thursday December 12, 2019 @11:33AM (#21773314)
Is there a way to trigger something after state changes ? In the class based components, setState has a second argument that gets triggered after state has updated.

This is nowhere to be found in the hooks approach, without using flags and other strange constructs.

Where is it gone ?

Re:Thinking in React Hooks by sombremesa on Thursday December 12, 2019 @11:38AM (#21773379)
You can use useEffect for this. If you only care about certain state/props, put them in the second argument in an array.
Re:Thinking in React Hooks by gherkinnn on Thursday December 12, 2019 @11:39AM (#21773392)
Use useEffect.

const [thing, setThing] = useState(true)

useEffect(() => { console.log({ thing }) }, [thing])

Re:Thinking in React Hooks by rpastuszak on Thursday December 12, 2019 @12:16PM (#21773848)
Not that it matters too much given the question asked, but am I right to think that the useEffect callback would get fired on the next render (function call) here?
Re:Thinking in React Hooks by lilactown on Thursday December 12, 2019 @12:26PM (#21773958)
The function given to useEffect will be fired after a successful _commit_ (aka React actually manipulates the DOM after a render).

Here's a helpful diagram that shows the difference between render and commit phases in terms of the class lifecycle methods: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram...

So when a render executes useEffect with a callback (and values in its dependency array has changed), it will schedule the callback to be run once React has committed the DOM changes based on the current render.

Re:Thinking in React Hooks by Klathmon on Thursday December 12, 2019 @02:15PM (#21775218)
And to add on to the other commenter, there's also a `useLayoutEffect` hook which fires synchronously after a react render but before the browser paints the render.

Basically `useLayoutEffect` fires in the same phase as `componentDidUpdate`, but it's discouraged unless you really need that timing (to do things like read the DOM directly and/or trigger a re-render before paint)

https://reactjs.org/docs/hooks-reference.html#uselayouteffec...