React
is a very dynamic environment, it is changing, updating and developing quite rapidly and hooks are the latest and a very significant implementation into React logic. You cannot say that hooks made classes, render props, aka previous way of doing things, obsolete, however hooks makes using React way simpler and more intuitive.The developers made possible for hooks to be opted-in so you don't have to rewrite your code completely. Before, render props there were mix-ins and they were removed.
Hooks are solving the problem of adding state to the stateless functional component. If you created a stateless functional component but then at some point you would have to add state to that component you would have to turn it into class component and it can be very difficult.
Hooks are made to inject functionality into "dumb" components. Hooks can be created by developers and implemented for specific problems along the way,there are some very popular like: Context hooks
, Effect hooks
, Reducer hooks
and Ref hooks
however, the most usable hook right now is State hooks
- useState
.
State Hooks
useState
is a replacement of a SetState
component in a class syntax. Before executing a return
, useState
declares a 'state' variable, that way we can 'save' some values, between invocations. It is a way substitute this.state
functions. useState
returns a couple of values: present state and a function that refreshing the state.
Effect Hooks
useEffect
hook allows you to access the data inside the component. Effect hooks can be used as a substitute to the lifecycle methods like: "Component Did Mount", "Component did Update" and "Component will Unmount". What it does is, when you have an "unpure" function and you don't have a React component,
you do have to write code for those components. Effect hook solves this problem. Also, previously you had to pass logic into each component and it could lead to potential difficulties, however now, you can build a special hook to store that logic.
Reducer Hooks
useReducer
hook is a less used, however it allows functional components in React access to reducer functions from your state management. Reducer is a function that takes in the current state,as well as a specified action. Inside of your reducer function you can store multiple use cases. According to the use case you can access specific data return an updated state.
Top comments (0)