Toggle Boolean State Effectively in React

August 18, 2022

Introduction

If we want to preserve some state in the React application, we are using an useState hook. It is not bad, but is there any other option? Let's explore!

Let's create a custom hook that will return two values - the state and a function to update the state.

useState implementation

index.tsx
import { useState } from 'react'
type UseToggleReturnType = {
isToggled: boolean
toggle: () => void
}
export const useToggle = (): UseToggleReturnType => {
// We do not need to export the `setIsToggled` function, as we want to simplify the hook usage.
const [isToggled, setIsToggled] = useState(false)
// Instead of providing the `setIsToggled` function, we have a specialized function to toggle the current state for us
const toggle = () => {
setIsToggled(!isToggled)
}
return { isToggled, toggle }
}

Tests

As you may know, I'm a big fan of testing, so let's implement some tests!

index.tsx
import { act, renderHook } from '@testing-library/react'
import { useToggle } from './use-toggle'
// assert that state and function to toggle the state are returned
describe('useToggle - return type', () => {
const { result } = renderHook(() => {
return useToggle()
})
it('should return an object with a `isToggled` property, which is false', () => {
expect(result.current).toHaveProperty('isToggled')
expect(result.current.isToggled).toBe(false)
})
it('should return an object with a `toggle` property, which is an function', () => {
expect(result.current).toHaveProperty('toggle')
expect(result.current.toggle).toBeInstanceOf(Function)
})
})
// verify if the state is updated when the toggle function is called
describe('useToggle - toggling', () => {
it('should run the `toggle` function and check if `isToggled` is set to `true`', () => {
const { result } = renderHook(() => {
return useToggle()
})
expect(result.current.isToggled).toBe(false)
act(() => {
result.current.toggle()
})
expect(result.current.isToggled).toBe(true)
})
})

useReducer implementation

As we have tests already implemented, we can use the useReducer hook to implement the same functionality.

Why useReducer? Because it is a more powerful version of useState, which allows us to use a reducer function to update the state based on the previous state.

index.tsx
import { useReducer } from 'react'
type UseToggleReturnType = {
isToggled: boolean
toggle: () => void
}
export const useToggle = (): UseToggleReturnType => {
// When calling a `toggle` function, a callback passed to the `useReducer` will be called with the previous state, returning the opposite state.
const [isToggled, toggle] = useReducer((previousValue) => {
return !previousValue
// `false` is the initial state
}, false)
return { isToggled, toggle }
}

Tests are still passing, and now we can use the useReducer hook to implement the same, but with a more robust approach.

Conclusion

The aim of this article was not to show shorter code or to create some library but to show how to use the useReducer hook instead of the useState hook for managing the state that should be toggleable.

Have you found any bugs, or do you have any questions? Feel free to reach out on Twitter.

If you do not want to miss the next article, click on the follow button!

Share this post on Twitter