React useSet Hook

ReactReactBeginner
Practice Now

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

Introduction

In this lab, we will explore how to create a stateful Set object in a React component using the useSet hook. This hook provides a simple and efficient way to manipulate a set of values in a component and can be customized to fit the specific needs of the application. By the end of this lab, you will have a better understanding of how to implement and use this powerful hook in your React projects.


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(("`React`")) -.-> react/PerformanceOptimizationGroup(["`Performance Optimization`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") react/PerformanceOptimizationGroup -.-> react/memoization("`Memoization with useMemo`") subgraph Lab Skills react/jsx -.-> lab-38409{{"`React useSet Hook`"}} react/event_handling -.-> lab-38409{{"`React useSet Hook`"}} react/hooks -.-> lab-38409{{"`React useSet Hook`"}} react/use_state_reducer -.-> lab-38409{{"`React useSet Hook`"}} react/memoization -.-> lab-38409{{"`React useSet Hook`"}} end

React useSet 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.

This function creates a Set object with state and a set of functions that can manipulate the state.

To use this function:

  • Call useState() and the Set constructor to create a new Set from the initialValue.
  • Use useMemo() to create a set of non-mutating functions that can manipulate the set state variable. Use the state setter to create a new Set every time.
  • Return both the set state variable and the created actions.

Here's an example implementation of this function:

const useSet = (initialValue) => {
  const [set, setSet] = React.useState(new Set(initialValue));

  const actions = React.useMemo(
    () => ({
      add: (item) => setSet((prevSet) => new Set([...prevSet, item])),
      remove: (item) =>
        setSet((prevSet) => new Set([...prevSet].filter((i) => i !== item))),
      clear: () => setSet(new Set())
    }),
    [setSet]
  );

  return [set, actions];
};

Here's an example usage of this function:

const MyApp = () => {
  const [set, { add, remove, clear }] = useSet(new Set(["apples"]));

  return (
    <div>
      <button onClick={() => add(String(Date.now()))}>Add</button>
      <button onClick={() => clear()}>Reset</button>
      <button onClick={() => remove("apples")} disabled={!set.has("apples")}>
        Remove apples
      </button>
      <pre>{JSON.stringify([...set], null, 2)}</pre>
    </div>
  );
};

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

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 useSet Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like