React useDefault Hook

ReactReactBeginner
Practice Now

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

Introduction

In this lab, we will be exploring how to create a custom hook called useDefault in React. The purpose of this hook is to create a stateful value with a default fallback if it's null or undefined, and a function to update it. By the end of the lab, you will have a better understanding of how to use custom hooks to simplify your React code and make it more efficient.


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-38379{{"`React useDefault Hook`"}} react/event_handling -.-> lab-38379{{"`React useDefault Hook`"}} react/hooks -.-> lab-38379{{"`React useDefault Hook`"}} react/use_state_reducer -.-> lab-38379{{"`React useDefault Hook`"}} end

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

Here is the code:

const useDefault = (defaultState, initialState) => {
  const [value, setValue] = React.useState(initialState);
  const isEmpty = value === undefined || value === null;
  return [isEmpty ? defaultState : value, setValue];
};
const UserCard = () => {
  const [user, setUser] = useDefault({ name: "Adam" }, { name: "John" });

  return (
    <>
      <div>User: {user.name}</div>
      <input onChange={(e) => setUser({ name: e.target.value })} />
      <button onClick={() => setUser(null)}>Clear</button>
    </>
  );
};

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

To create a stateful value with a default fallback, use the useState() hook in React. Check if the initial value is either null or undefined. If it is, return the defaultState instead, otherwise return the actual value state and the setValue function. The code above shows how to implement this functionality in a custom hook called useDefault.

In the example provided, useDefault is used to create a user state with a default value of { name: 'Adam' }. The initial state is set to { name: 'John' }. In the UserCard component, user is displayed along with an input field to update its name. A clear button is also provided to reset the state to null. Finally, the component is rendered using ReactDOM.createRoot().

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

Other React Tutorials you may like