React Hooks are v16.8 specification which allows certain backward compactible functionalities without any use of class based ordering.
Let's see an optimal state management technique for mid-size web apps.
TL;DR
To avoid the mess of passing props down to level infinity(prop drilling) of component tree we use useContext or so called ContextAPI, which creates a global state for ease of prop access down to infinite levels of component tree.
ContextAPI
Whenever you hear ContextAPI there exists two concepts which are of atmost importance:
- Provider
- Consumer
Let's hear what contextAPI has to say,
There is a global state which is provided to the root component so that the whole component tree is now avail of the global state and can be consumed in ease.
- Create a context
const myContext = React.createContext();
- Provide the same to the root component
globalState is the collection of all states and functionalities to be used in whole application.
we can integrate useReducer for creating the global state
<myContext.Provider value = {{ globalState }}>
<App />
</myContext.Provider>
- Consume wherever required
Here we can pull only the required data from the globalState by destructuring
const { requiredData } = useContext(myContext);
ContextAPI in action
Let's see an example of how to actually use them.
Here we have some people's data and a remove function as globalState
import React, { useState, useContext } from 'react';
import { data } from '../../../data'; //people's data
const PersonContext = React.createContext();
const ContextAPI = () => {
const [people, setPeople] = useState(data);
const removePerson = (id) => {
setPeople((people) => {
return people.filter((person) => person.id !== id);
});
};
return (
<PersonContext.Provider value={{ removePerson, people }}> //pass the global state as props
<h3>ContextAPI in Action</h3>
<List />
</PersonContext.Provider>
);
};
const List = () => {
const mainData = useContext(PersonContext); //here we pull of the people data
return (
<>
{mainData.people.map((person) => {
return (
<SinglePerson
key={person.id}
{...person}
/>
);
})}
</>
);
};
const SinglePerson = ({ id, name }) => {
const { removePerson } = useContext(PersonContext); //here we pull of remove function
return (
<div className='item'>
<h4>{name}</h4>
<button onClick={() => removePerson(id)}>remove</button>
</div>
);
};
export default ContextAPI;
This may seem a bit confusing but worth learning, the same example done manually with prop drilling would get you in trouble.
Major Takeaway
useContext hook is a optimal solution for prop drilling and a state management technique in mid-size applications.
Let's connect ๐
Catch me here ๐
Hope you all liked the post, share your impressions and queries below ๐