25 / 06 / 2022

32. useState

React Hooks are very useful tools in building the web applications. The first one I would like to introduce is useState. useState returns a stateful value, and a function to update it. When we using useState, we need to define the name of the state and the function as belows:
const [state, setState] = useState(initialState);

The initial state can be set by passing a data type. During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState). The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component. During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates. We can also change the state based on current state. It is easy and convenient to manipulate the state by using useState.