This repo contains all the implemenations of react hooks
- In classes state is always an object but in useStateHook the state dosent have to be an object
- When dealing with objects and arrays, always make sure to spread your state and then call the setter function
- When we use useEffect without second argument it calls the funtion everytime a component updates It is similar to componentDidUpdate
useEffect(() => {
document.title = `Count = ${count}`;
});
- When the variables in the array updates then only the below useEffect runs It is similar to conditional componentDidUpdate
useEffect(() => {
document.title = `Count = ${count}`;
}, [count]);
- When we give empty array then it acts as componenetDidMount and it will run only once
useEffect(() => {
console.log("Run only once");
}, []);
- To make cleanup function to cancel all listners we can return a function and have the clean up code It is same as componentDidUnmount
useEffect(() => {
document.title = `Count = ${count}`;
return () => {
//Your clean up code here
};
}, [count]);
Eg of how to create context
export const UserContext = React.createContext();
<UserContext.Provider value={"Avash"}>
<UseContext></UseContext>
</UserContext.Provider>
This is where we want to use the context info
import { context_name } from "../../App";
and then inside function
const variable = useContext(context_name);
- Its used for state management
- useState is built using useReducer
const reducerFunction = (currentState, action) => {
// code
return newState;
};
const [newState, dispatch] = useReducer(reducerFunction, initialState);
//To call a reducer use
dispatch(action_type);
Scenario | useState | useReducer |
---|---|---|
Type of state | Number,string or boolean | Object and array |
Number of state transitions | One or two | Too many |
Related state transitions | no | yes |
Local vs global | Local | Global |