Hooks are an essential part in React and understanding their behavior is a key to produce effective React code.
In this article we gonna cover essential hooks that React provides and understand their behavior.
useState
The state hook is a hook that will provide an internal state to the component.
It will work the following way.
On the first load it gonna take the data passed as parameter will be used to initialize the state from the component.
The hook will return two values:
- The current value from the state.
- A method to update the value state.
On update from the component due to the set state method the hook will return this time the new value instead of the initial one.
On an update from the component not due to the set state method then the value from the test won’t change event if the value passed as parameter to the state initialization changes.
useReducer
The reducer hook is an state hook with more flexibility.
Instead of having a hook that just stores values it is now using a function to modify it.
To initialize this hook two values needs to be provided:
- A function called to update the state.
- A initial value for the state.
On the first load the reducer will react the same way as the the state hook works.
However on the update from the value from the state the logic will differ from the other hook as here the function passed the hook will be used by the hook hook to define the next step instead of just storing the new value and return it.
useEffect
The hook useEffect is here to run actions only when some parameters values are changed.
If not parameter is provided then it will only be executed when the component is mounted for the first time.
This hook also offer a clean up method that would execute only when the component is unmounted.
On a regular workflow the hook will first execute when the the component will mount for the first time.
Then it will re execute each time of the parameters given is changing.
Finally it will execute the clean method when the component is unmounted.
useContext
The first thing to understand before using that hook is what is a context.
The useState or the useReducer hooks are really useful but they have a main default.
Both of them are local to the component the hook is called in and to share it to another component the only way is to pass it by the props.
This would make the code really bug prone especially when there are multiple layers of components to pass through.
To prevent this contexts has been introduced into React allowing a component to share its state with its children without using props.
This allow each children to have the value from the context but not to modify it. That’s why the value from the context is often the results from a useState hook.
This way the value transmitted to the children include the value from the state but also the method to update it. This way now children component are able to modify the content from the state.
Laisser un commentaire