This content originally appeared on DEV Community and was authored by Dimer BWimBA
You'll already know now The React framework includes react hooks. Witch are Special hook functions that can be called from within a component.
function component(){
//your react hook
return <>UI</>
}
So By defining functions, we may create static or dumb react components. And UI components, on the other hand, are frequently dynamic; they may need to change the state of their data, respond to lifecycle events
, and access items from the DOM
, among other things.
1) Reactive State >
function Component(){
const [state] = useState('?')
return <>UI</>
}
2) Side Effects > ? > Effects > ?
function Component(){
useEffect(() => alert('?'))
return <>UI</>
}
3) Grab > HTML5 > Elements > ⭐
function Component(){
const el = useRef('?')
return <>UI</>
}
...more
?????
But prior to react version 16.8
, developers were required to write classes to take advantage of certain react features.
?????
Before
class btn extends React.Component{
constructor(props) {
super(props);
this.state = {
count:0
}
}
render() {
return (
<p>{this.state.count}</p>
);
}
}
????
After
function Btn(){
const [state] = useState({count:0})
<p>{state.count}
}
Now you can still use classes
in react ?...
But hooks
? generally provide a more ergonomic way to build components because you can reuse stateful logic without changing your component hierarchy.
???React has 10 built in hooks, and you'll understand what every single one of them does by the end of four part series 'articles'. In addition, you'll learn how to build your own hooks from scratch to extract your own component logic into reusable functions ???. So follow me bruh , let learn together .
#let gooooo #????
Before we dive into the react hooks world ??, it's helpful to understand why hooks exist in the first place. In the past stateful logic or data that changes within the application was tightly coupled to a class based component. That means in order to work with reactive data, you needed to create a component that seems reasonable. But what it led to in reality was a complex tree of nested components.
??And this is where I have to admit that I used to really dislike and I never learned react because sharing any logic required some frustrating ? jujitsu like higher order components and render props, which are patterns that have you passing components as arguments to other components. And that just always felt way more complex to me than patterns you find in other frameworks like Angular.
? Fortunately, ? hooks changed everything by giving you access to lower level features of react outside of the context of a component. When you work with hooks, you can think of them like low level primitives of the React framework that gives you special abilities that you wouldn't otherwise have in vanilla JavaScript. The hooks themselves are functions, which always start with the name of use
, because you're using the super powers of the React framework. Now before you start using hooks, there's really just one rule you should be aware of.
And that's to only call them at the top level of a functional component.
They don't work inside of regular JavaScript functions, nested functions, loops, or anything like that.
The only exception to this rule is when building your own custom hooks, which we'll look at towards the end of these 'articles'.
Now the question becomes, what are these primitives or hooks actually do?
Let's break them down one by one, starting with useState
.
useState
is easily the most important and often used hook . The purpose ofuseState
is to handle reactive data. any data that changes in the application is called state. And when the state changes, you want react to update the UI. So the latest changes are reflected to the end user.
The hook takes one optional argument, which is the default state, which we'll go ahead and set to zero the function and returns an array that contains two values you can use within your component.
The reason they're returned in an array is because we can destructur them with JavaScript to easily assign the values to local variables that we can name whatever we want.
The first value is the reactive data or state. If we then reference it in the UI, and its value changes in the future, React will automatically rebuild the UI to show the latest value, it'll start with a value of zero our default in the hook.
But how do we then change its value in the future, the second element in the array is a setter function. For example, we might listen to the on click event on the button, and when clicked will call the set count function to increment the count by one.
?If we compare this code to a class based component, you can see
down bellow it's far more complex.
?We need a class to extend a react component than a constructor to initialize the state. And also notice how we're required to reference the this keyword all over the place. You state in my opinion is a much cleaner solution.
Now we're ready to tackle the second most important hook useEffect
.
Also happens to be one of the most #confusing to me and many other . So in order to understand it, you first need to understand the component lifecycle
.
Down below is a simplified breakdown of the component lifecycle, the component is added to the UI or mounted, which can only happen once then reactive data on the component can change or it's updated, which can happen multiple times. Then finally, at some point, that component will be removed from the UI or unmounted.
Now keep these three lifecycle events
or side effects
in mind as we talk about the use effect hook, which allows us to implement logic for all of them from within a single function API.
UseEffect
is a function that takes a function you define as its first argument, React will then run your function or a side effect after it is updated the DOM with the current implementation, it will run this function anytime stateful data changes on the component. That means it'll run once when the component is initialized with a default value, then run again each time the state or account is updated.
???In most cases, though, you'll likely want more fine grained control over that behavior. For example, imagine we need to fetch data when the component is first initialized, then update the state asynchronously after the data has been fetched.
This previews code in the image would result in an infinite loop. Because every time we do the fetch, we then update the state, which then triggers another fetch, and so on forever.
The way we address this is by adding a second argument to use a fact, which is an array of dependencies. If you add an empty array, it means there are no dependencies, which means it will only run once when the component is first initialized. But in other cases, you might want to rerun the function anytime certain staple data has changed, you can do that by adding the state to the dependencies array.
Now react will track that value, and any time it changes, it will rerun this function.
Now one last thing you might want to do with useEffect
is run some teardown code when the component is destroyed. The way we implement a teardown function is to return a function from our use effect callback, React will take the function returned here, then call it when the component is destroyed.
And with that, let's move on to our next hook use context.
This hook allows you to work with react context API, which itself is a mechanism that allows you to share or scope values throughout the entire component tree.
Part 2 Tomorrow
This content originally appeared on DEV Community and was authored by Dimer BWimBA
Dimer BWimBA | Sciencx (2021-05-30T11:23:52+00:00) Understand React Js Hooks once and for all | part I. Retrieved from https://www.scien.cx/2021/05/30/understand-react-js-hooks-once-and-for-all-part-i/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.