DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 12

Today's task is to implement a useToggle hook. The boilerplate function is


export function useToggle(on: boolean): [boolean, () => void] {
  // your code here
}


// if you want to try your code on the right panel
// remember to export App() component like below

// export function App() {
//   return <div>your app</div>
// }

Enter fullscreen mode Exit fullscreen mode

The first step is to create the variables to switch between states. There are only 2 states, because the purpose of a toggle is to alternate between either of them - on and off or checked and unchecked.

const [value, setValue] = useState(on)
Enter fullscreen mode Exit fullscreen mode

The next step is to create the function to switch between states.

const toggle = () => {
  setValue(!value)
}
 return [value, toggle]

Enter fullscreen mode Exit fullscreen mode

To see an example, there would be a button which, when clicked, switches the state of the app

export function App() {
 const[on, toggle] = useToggle(false)
 return(
 <div>
 <p>{on ? "On" : "Off"}</p>
 <button onClick{toggle}> Toggle </button>
 </div>
 )
}
Enter fullscreen mode Exit fullscreen mode

The final code looks like this:

import React, { useState } from 'react';
export function useToggle(on: boolean): [boolean, () => void] {
  // your code here
   const [value, setValue] = useState(on)

    const toggle = () => {
      setValue(!value)
    }
    return [value, toggle]

}


// if you want to try your code on the right panel
// remember to export App() component like below

export function App() {
  const [on, toggle] = useToggle(false)
  return <div>
  <p>{on ? "On" : "Off"}</p>
  <button onClick={toggle}>Toggle</button>
  </div>
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)