Hooks
Hooks allow functions to have access to state and other React features without using classes.They provide a more direct API to React concepts like props, state, context, refs, and lifecycle.
Hook Rules
There are 3 rules for hooks:
- Hooks can only be called inside React function components.
- Hooks can only be called at the top level of a component.
- Hooks cannot be conditional
Types of React Hooks:
- useState
- useEffect
- useContext
useState
The useState hook is used to declare state variables in functional components. It allows us to read and update the state within the component.
const [state, setState] = useState(initialState);
- state:The current value of the state.
- setState: A function used to update the state.
- initialState: The initial value of the state, which can be a primitive type or an object/array
import {useState} from 'react';
function Name(){
const [changeName, setChangeName] = useState("Ganapathi");
function changeFunction(){
if(changeName === "Ganapathi"){
setChangeName("Veera");
}
else{
setChangeName("Ganapathi");
}
}
return(
<div>
<h1>NameChange</h1>
<p>{changeName}</p>
<button onClick={changeFunction}>NameChange</button>
</div>
)
}
export default Name;
Output:

Top comments (0)