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>
// }
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)
The next step is to create the function to switch between states.
const toggle = () => {
setValue(!value)
}
return [value, toggle]
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>
)
}
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>
}
Top comments (0)