React Hooks

Shunze
1 min readFeb 4, 2021

--

The actual content comes from Kent C. Dodds.’s Epic React Course.

useState

useState is a function that accepts a single argument which is the initial state.

useState returns a pair of values.

The first of the pair is the state value and the second is a function we can call to update the state.

What is State?

State can be defined as: data that changes over time.

Lazy State Initialization

useState allows us to pass a function instead of the actual value, and then it will only call that function to get the state value when the component is rendered the first time.

useEffect

useEffect is a built-in hook that allows us to run some custom code after component render and re-render.

It accepts a callback function which React will call after browser painting.

But there are various reasons a component can be re-rendered like when a parent component in the application tree gets re-rendered.

So we need a way to prevent side effects run frequently.

Dependency Array

useEffect allows us to pass a second argument called the “dependency array” which signals to React that your effect callback function should be called when (and only when) those dependencies change.

--

--

No responses yet