React Hooks Tutorial for Beginners | Ultimate Guide to Learn
Last updated on 11th Aug 2022, Blog, Tutorials
Introduction to React
React is a UI building framework which helps to build well-managed & well-structured Interfaces by abstracting away the important complications faced while building them.
If building a UI which reacts to changes in related data, React is a very good fit for the development stack.
What are Components?
In React, a component is a piece of the UI which holds its own data, referred to as state, and returns rendered HTML based on the information.
Additionally, components are in charge of their own state.
This means that functions updating component state require to be present in the scope of the component.
It results in well structured code which is simple to read & understand.
React also does not enforce the granularity of components.
A component can include as more or as little UI parts feel are required.
Comparing Class Components & Hooks
Class components are written in an object oriented way, with every function written as an object of the class and extensive use of “this” operator.
This used to be the preferred way of writing components in the past because state handling & lifecycle methods are not usable in Functional Components.
The introduction of Hooks makes Functional components as useful.
Basic React Hooks
There are 10 in-built hooks that shipped with React 16.8 but the basic hooks include:
- useState()
- useEffect()
- useContext()
- useReducer()
The useState() hook receives the first state as an argument and then returns, by making use of array destructuring in JavaScript, the 2 variables in the array can be named what. The 1st variable is the actual state, while the 2nd variable is a function that is meant for updating the state by providing a new state.
The useEffect() hook accepts a function that contains effectual code. In functional components, effects like mutations, subscriptions, timers, logging, and other effects are not allowed to be located inside a functional component because doing so would lead to a lot of inconsistencies when the UI is rendered and confusing bugs.
The useContext() hook accepts a context object that is the value returned from React. createContext, then it returns the current context value for that context. This hook gives functional components simple access to React app context. Before the useContext hook was introduced it would need to set up a contextType or a to access global state passed down from some provider in a class component.Basically, the useContext hook works with the React Context API which is a way to share data deeply throughout the app without the need to manually pass app props down through different stages.
Now, the useContext() makes using Context a little simpler. To explain the useContext method we will rewrite the Display component using the useContext hook. The useReducer hook is used for handling difficult states and transitions in state. It takes in a compressor function and also an initial state input; then, it returns the current state and also a dispatch function as output by the means of array destructuring.
Five Important Rules for Hooks
- 1. Don’t call Hooks from inside a loop, condition or nested function
- 2. Hooks should sit at the top-level of the component
- 3. Only call Hooks from React functional components
- 4. Don’t call a Hook from a regular function
- 5. Hooks can call other Hooks
Stateful vs. Stateless Components
A stateful component declares and maintains local state in it.
A stateless component is a pure function that doesn’t have a local state and side-effects to maintain.
A function that has no side effects is said to be pure.
This implies that a function always yields a comparable result for a comparable input.
If you take out the stateful and side-effects logic from a functional component, have a stateless component.
Also, the stateful and side-effects logic can be reused elsewhere in the app.
It makes sense to isolate them from a component as much as possible.
React Hooks and Stateful Logic
With React Hooks, it can isolate stateful logic and side-effects from a functional component.
Hooks are JavaScript functions that maintain the state’s behavior and side effects by isolating them from a component.
Isolate all the stateful logic in hooks and use them into the components.
React provides a bunch of standard in-built hooks:
useState:To maintain states. Returns a stateful value and an updater function to update it.
useEffect:To maintain side-effects like API calls, subscriptions, timers, mutations, and more.
useContext:To return the current value for context.
useReducer:A useState alternative to help with difficult state management.
useCallback:It returns a memorized version of a callback to help a child component not re-render unnecessarily.
useMemo:It returns a memoized value that helps in performance optimizations.
useRef:It returns a ref object with a .current property. The ref object is mutable.
It is majorly used to access a child component imperatively.
useLayoutEffect:It fires at the end of all DOM mutations.
It’s best to use useEffect as much as possible this one as the useLayoutEffect fires synchronously.
useDebugValue:Helps to view a label in React DevTools for custom hooks.
Advantages of React Hooks
React Hooks makes life easier in a lot of ways as stated below:
Improving Readability of Component Tree
The “useContext” hook has been a blessing for highly improving the readability of JSX as it allows context values to be read outside of JSX.
This is also previously possible in the class components by using the static “contextType” property but is even cleaner with “useContext”.
Aside from the code being simple to read it is also much easier to read the component tree in the React dev tools when debugging.
The value of this really adds up for components that previously used multiple nested contexts.
Encapsulating Side Effects
With class components, the setup and teardown of side effects were split across the multiple lifecycle methods like the event listeners could be added in “componentDidMount” and later removed in “componentWillUnmount”.
If any component has multiple side effects this could lead to less readable code with a related logic split across the several incohesive lifecycle methods.
But the “useEffect” solved this problem by handling both the setup and teardown of side effects.
It does so by allowing the effect function to return a function to teardown the effects.
Are you looking training with Right Jobs?
Contact Us- Windows Azure Interview Questions and Answers
- Salesforce Architecture Tutorial
- Wrapper Class in Salesforce Tutorial
- salesforce lightning
Related Articles
Popular Courses
- VM Ware Training
11025 Learners
- Microsoft Dynamics Training
12022 Learners
- Siebel Training
11141 Learners
- What is Dimension Reduction? | Know the techniques
- Difference between Data Lake vs Data Warehouse: A Complete Guide For Beginners with Best Practices
- What is Dimension Reduction? | Know the techniques
- What does the Yield keyword do and How to use Yield in python ? [ OverView ]
- Agile Sprint Planning | Everything You Need to Know