Written by Phuong Nguyen – Software Engineer, Atlantic Team
In the previous part, we covered some general information about custom hooks and how to create them. Now, let’s dive deeper into specific examples and practical applications to unleash their potential to improve the development experience.
Some examples of Custom Hooks:
1. useToggle: The function to change the value of the state variable.
In the body of the function, we:
– Create a state containing the value of the variable.
– In this custom hook, create a toggle function to receive the next click event that calls to this action.
– To prevent the function’s address from being changed after each render, we call the function use Callback to cache the data and avoid unnecessary re-rendering in components using it.
– Next, we call the function to setState again. Remember that we will have to use the setState function with a Callback function as a parameter. The callback function has a state parameter that ensures the state is always up to date.
Note: If we change the setState parameters to !isToggle, this custom Hook will re-render only the first time we call the onClick event. If we remove use Callback, then the state will be re-rendered to normal. The use Callback function rerenders to update the state when dependencies change. Its state will freeze until the second parameter changes. The second parameter here is the empty array, so the Toggle variable inside the function will always be equal to defaultValue.
– Finally, we will return an array of 2 parameters respectively, state and the function change state. For components to use it, they can display this variable on the screen.
Use in component:
2. usePrevState: The parameters in the class component’s function will usually have previousState and previousProps parameters. In hooks, we have some ways to implement it but the clearest and most reusable way is to use usePrevState.
– First, run usePrevState with props which is the state of the component.
– When entering the usePrevState function, it will initiate a ref because when the ref changes, the custom hooks do not re-render. When custom hooks re-render, the parent component must reRender and PrevState is no longer the previous state, it is the current state.
– Next, we set a use Effect with the being the props as the second parameter containing the latest state of the component passed. Its purpose is to update the latest value of the parent component for Hooks.
– Next, we return the value of the previous state.
Note: The returned value is the previous state’s value. After returning, it will call the use Effect function to update the current value of the state. After updating, the next time the state changes, it will return to this value.
3. State Management: Custom hooks can manage states using hooks like useState. They allow you to encapsulate stateful logic into a reusable function, making it easier to handle and update states in multiple components.
In this example, we define a custom hook called use Counter that manages a count state.
The hook returns an object with three properties: count, increment, and decrement.
The count property holds the current value of the count state, while increment and decrement are functions that allow us to update the count state.
4. Side Effects: Custom hooks can handle side effects using hooks like use Effect. This enables you to encapsulate common side effect logic (such as data fetching, subscriptions, or event listeners) and reuse it across different components.
5. Context Access: Custom hooks can access and consume context using the useContext hook. This allows you to encapsulate context-specific logic into a custom hook, making it more reusable and easier to maintain.
6. Logic Abstraction: Custom hooks enable you to abstract complex logic from components into reusable functions. This promotes code organization and readability, as the components become more focused on rendering UI and less cluttered with intricate logic.
This custom hook allows us to abstract the logic for counting with a variable increment and reuse it in different components. We can easily modify the initial value and the increment value based on our requirements. This promotes code reusability and maintains consistency in the counting logic across components.
7. Code Reusability: One of the primary benefits of custom hooks is code reusability. By extracting common logic into a custom hook, you can reuse it across multiple components, avoiding code duplication and ensuring a more maintainable codebase.
By utilizing the custom hook, we can easily reuse the logic for generating a greeting message in different components. We pass different names as parameters to the custom hook, enabling personalized greetings for ReactJS and React Native users.
8. Separation of Concerns: Custom hooks allow for better separation of concerns by separating UI-related code from the underlying logic. This separation promotes cleaner and more modular code architecture, making it easier to understand and maintain the different aspects of your application.
We separate the concern of data fetching from the components. The components only focus on rendering the UI based on the fetched data, loading state, or error state.
In conclusion, custom hooks provide a powerful way to extract and reuse stateful logic in ReactJS and React Native applications. They enable us to encapsulate complex functionality into reusable functions that can be shared across multiple components.
With custom hooks, we can improve code organization, promote code reusability, and enhance the separation of concerns within our applications. By abstracting logic into custom hooks, our components become more focused, concise, and easier to understand.
We explored various use cases of custom hooks, such as state management, handling side effects, accessing context, abstracting logic, improving testing, and facilitating collaboration and code sharing. Custom hooks allow us to create modular, maintainable, and scalable codebases.
So, next time you find yourself writing similar logic across different components, consider creating a custom hook. Embrace the power of custom hooks to enhance code reusability, promote separation of concerns, and simplify development in ReactJS and React Native.
If you are finding Part 1 of this session, please click HERE!