React useToggler Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the useToggler hook in React. This hook provides a simple and efficient way to create a boolean state variable that can be toggled between its two states. By the end of this lab, you will have a better understanding of how to use this hook in your React applications to create toggle functionality for your components.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38413{{"`React useToggler Hook`"}} react/event_handling -.-> lab-38413{{"`React useToggler Hook`"}} react/conditional_render -.-> lab-38413{{"`React useToggler Hook`"}} react/hooks -.-> lab-38413{{"`React useToggler Hook`"}} react/use_state_reducer -.-> lab-38413{{"`React useToggler Hook`"}} end

React useToggler Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To create a boolean state variable that can be toggled between its two states, follow these steps:

  1. Use the useState() hook to create the value state variable and its setter.
  2. Create a function that toggles the value of the value state variable and memoize it, using the useCallback() hook.
  3. Return the value state variable and the memoized toggler function.

Here is an example implementation:

const useToggler = (initialState) => {
  const [value, setValue] = React.useState(initialState);

  const toggleValue = React.useCallback(() => setValue((prev) => !prev), []);

  return [value, toggleValue];
};

You can then use this hook in your components, like this:

const Switch = () => {
  const [val, toggleVal] = useToggler(false);
  return <button onClick={toggleVal}>{val ? "ON" : "OFF"}</button>;
};

ReactDOM.createRoot(document.getElementById("root")).render(<Switch />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useToggler Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like