React useGetSet Hook

ReactReactBeginner
Practice Now

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

Introduction

In this lab, we will be exploring the use of the useGetSet hook in React. This hook allows us to create a stateful value and retrieve or update its value using getter and setter functions respectively. By the end of this lab, you will have a better understanding of how to use this hook in your React applications.


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/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38386{{"`React useGetSet Hook`"}} react/event_handling -.-> lab-38386{{"`React useGetSet Hook`"}} react/hooks -.-> lab-38386{{"`React useGetSet Hook`"}} react/use_state_reducer -.-> lab-38386{{"`React useGetSet Hook`"}} end

React useGetSet 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 code snippet defines a custom React hook called useGetSet that creates a stateful value and returns a pair of functions for getting and setting its value. The Counter component uses this hook to implement a delayed increment of a count displayed in a button.

const useGetSet = (initialState) => {
  const stateRef = React.useRef(initialState);
  const [, update] = React.useReducer(() => ({}), {});

  const getState = React.useCallback(() => stateRef.current, []);
  const setState = React.useCallback((newState) => {
    stateRef.current = newState;
    update();
  }, []);

  return [getState, setState];
};

const Counter = () => {
  const [getCount, setCount] = useGetSet(0);
  const onClick = React.useCallback(() => {
    setTimeout(() => {
      setCount(getCount() + 1);
    }, 1000);
  }, [getCount, setCount]);

  return <button onClick={onClick}>Count: {getCount()}</button>;
};

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

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

Other React Tutorials you may like