Hooks are the new feature introduced in the React 16.8 version. Hooks permits to use state and other React features without writing a class. Hooks works as functions, “hook into” React state and lifecycle features from function components. Also, it does not replace your knowledge of React concepts.
Hooks have been announced at React Conf 2018.
Hooks provide a powerful way to combine state, props, components, refs, lifecycle.
Here is a list of hooks available. Apart from that there is always an option of re-using these and creating your own custom hooks to reuse stateful behavior between different components.
Yes, you heard that right! Doesn’t that sound cool?
In this article we will just cover the basics hooks in detail.
1. useState: New hook takes an object where we define the initial values and validate function, The function also returns an object. We are creating the values.Values and setValues will store and set the value of the form fields.
The component can modify its state.To enable state management for functional components we need useState() hook.
Initializing state, Reading state, Updating state with one single function call.
useState contains a pair: current state value and a function to update it. Just like below. It is similar as using this.setState in the traditional method.
import {useState} from 'react'; import { Text, TouchableOpacity } from 'react-native'; function Example() { // Declare a state variable, let’s call it "count" const [count, setCount] = useState('0'); return ( <> <Text>You clicked {count} times</p> <TouchableOpacity onPress={() => setCount(count + 1)}> Click me </TouchableOpacity> </> ); }
2. useEffect: useEffect is here for fetching data, changing things, Adding event listeners also.useEffect can be used to set up and shut down correctly as part of a component’s lifecycle.
3 most commonly used lifecycle methods are componentDidMount, componentDidUpdate and componentWillUnmount.
You might be wondering 🤔 how this single hook can serve the purpose of different lifecycle methods! The answer to this is yes that can happen. Let’s take an example of a BackHandler for the same.
import { BackHandler } from 'react-native';
function Example() { useEffect(() => { // This serves as componentDidMount BackHandler.addEventListener('backPress', handleBackButton); }); // This serves as componentWillUnmount return () => { BackHandler.removeEventListener('backPress'); }; }, []); const handleBackButton = () => { BackHandler.exitApp(); };
In the above example, the BackHandler listener will be removed when the component unmounts, as well as before re-running the effect due to a subsequent render.
3. useContext: useContext allows us to access context properties from anywhere within our components. If any prop needs to be passed through several components down the tree, useContext can be used. Let’s take an example where we have 3 components A->B->C in a hierarchy and we need to use a theme in Component C that has been provided in Component A, the prop need not be passed unnecessarily to Component B and can be directly consumed by Component C which is possible with useContext. useContext can be used like:
const value = useContext(MyContext);
Let’s take an example for the store:
const colors = { blue: "#03619c", yellow: "#8c8f03", red: "#9c0312" }; export const ColorContext = React.createContext(colors.blue);
Then, we can provide our context to whatever child component needs it. In this example, we create colors for the whole app, so we will wrap it in our App:
import { ColorContext } from "./ColorContext"; function App() { return ( ); }
We can use which is available in both class-based and functional components. It would look something like this to use
return ( {colors => ...} );
Yet, consuming our context in this manner is only available in the return block so can’t be accessed outside. To access it outside the JSX tag it can be out as
static contextType = ColorContext;
This works for class-based components but for functional components the same can be implemented with useContext as:
import React, { useContext } from "react" const MyComponent = () => { const colors = useContext(ColorContext); return ...; };
4. useRefs: These are probably used to access a DOM component directly or update the same. Here is an example of a DOM component ScrollView using useRef.
const scrollRef = React.createRef(); return ( ... ); // Can be used anywhere within the component outside render scroll.current.scrollTo({x: 0, y: 0, animated: true});
There are many hooks apart from these which we can cover in further articles. Apart from this using these hooks custom hooks can also be created.
At last I will only say as always, hope this article helps you in understanding the basic hooks concept like other articles of mine.
Keep Spreading Knowledge and Happy Coding!! 🙂🙂
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and MindBowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Our CISO was extremely impressed by Mindbowser’s work. It is pretty rare to see this kind of clean security report so early in the company’s journey. Huge Thank you for the disciplined approach here.
Founder, TrestleIQ
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
The flexibility and capacity of the Mindbower staff has been impressive.
CEO, ProofPilot
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.
Founder, Courtyardly
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork