π₯ Functional components were created for simplicity
Before hooks were introduced, we could only use class components. Class components were created by extending the React.Component main class like this:
import React from "react"
class myClassComponent extends React.Component{
//rest of component code
}
Classes easily became convoluted and had a lot going on so the React team decided to make things easier for developers by allowing us to create React components from regular JavaScript functions!
Now our components can look like something we are more familiar with:
import React from "react"
function myFunctionComponent(){
return(<>Hi!</>)
}
β Why we need hooks with functional components
As you probably know, the whole point behind using a front-end framework is to benefit from the capabilities offered by the framework. For example, React allows you to manage your component's state, lifecycle and many other things. Since class components were created by extending the React.Component main class (where all the main the amazing super powers of React reside), we can easily start using React features without importing any extra module.
But because functional components are pretty much JavaScript functions that want to behave like the traditional class components, they need to be injected with the React feature or ability they want to make use of. This is done through the use of React hooks. We're hooking functional components to a React-only ability or feature. A functional component doesn't necessarily need to use any hook - you only use the appropriate hook to serve a specific need.
Common Hooks:
Common Hooks include useState, useContext, useReducer and useEffect :
I will create posts on how to use these very soon.
Creating your own hooks
Did you know that you can create your own React hook? Yes, you can! Now, you might be wondering why you might want to do that:
Remember that hooks are there to tie/attach a React-only functionality to a functional component. For example, if you want to give a function the ability to use React's state object, perform an operation on it, and share it with multiple other components, then you may consider creating your own hook. When you create your own hook it means you want to use a React-only feature but not inside of a fully-fledged component - you just need that feature to do something that will implemented inside a fully-fledged functional component.
To make a hook, all you need to do is create a regular JavaScript function prefixed with the word "use" so that React knows it's dealing with a hook instead of a fully-fledged functional component.
//------Creating a hook------
import React, {useState} from "react"
function useMyHook(){
//My hooks's code! For example, I can use state, do something, then return it!
const [name,setName] = useState("Daniella")
return name
}
//------Using a hooking inside a functional component ------
function myFunctionalComponent(){
const name = useMyHook()
}