useState hook
Maya Ifrim

Maya Ifrim

Mar 24, 2023

useState hook

In React, state refers to an object that holds some information relevant to a component and can be used to dynamically change the content of a component. The state is mutable, meaning that its values can be updated over time.

To handle and manage state, the useState() hook is employed. This hook enables the creation, tracking, and updating of a state in functional components.

The useState hook is one of the most commonly used hooks in React, which is essentially a function that allows you to add state to a functional component.

useState accepts an initial state and returns two values:

- first value represents the current state

- second value is a function that updates the state

state.png

The example below is for a React component that displays a light/dark mode toggler which allows users to switch between the two modes by clicking the slider.

The state variable "isDarkMode" is initialized to true using the useState hook, and the "setIsDarkMode" function is used to update the state value.

usestate2.png

The className property of the main element is dynamically set based on the "isDarkMode" state value.

onClick event is used to toggle the isDarkMode state value by calling the setIsDarkMode() with a callback that takes the previous state value and negates it.

Output:

mode.png

Mutate state in a functional way

To update the state in a functional way, always use the updater function returned by the useState hook, rather than modifying the state value directly.

The updater function takes the previous state value as an argument and returns the new state value. This ensures that state updates are always based on the current state value and avoids issues like race conditions.

In the example above, setIsDarkMode() takes a callback that receives the previous state value as an argument (prevMode) and returns the new state value (!prevMode). This ensures that the state is updated in a functional way and avoids any issues that may arise from concurrent state updates which means the state is set in a functional way.

By grabbing the value of the previous state, React can properly batch all the requests and update state linearly and no information is lost in the middle.

Maya Ifrim

Maya Ifrim

Passionate React developer with a love for crafting beautiful and user-friendly interfaces.

Leave a comment

Related Posts

Categories