Basic React Hooks explained - useState
useState - Godfather of the hooks
useState is probably the most used and common hook. It is the simplest way to have a state in a functional component.
SYNTAX
const [value, setValue] = useState(initialValue)
- useState returns an array
- first item is the value of the state
- second item is a method to set the state
- const [value, setValue] = useState(initialValue)
WHAT HAPPENS WHEN YOU SET IT?
You should set values in event handlers or within other hooks like useEffect, because the change triggers a rerendering. Re-rendering should be only done when the rendering of the component is finished.
function SomeDumpComponent() {
const [text, setText] = useState('')
setText('A new text');
// here the rendering of the component is not finished.
// The code below for rendering is not executed.
// This can cause side-effects.
return(<h1>{ text }</h1>);
}
EXAMPLE
Below you have a component which shows a message.
- The message text is the state of the component
- When the message text changes the component is re-rendered
- setText is called within the onClick event. So the rendering of the component is finished and we call setText without problems.
export function MessageComponent() {
const [text, setText] = useState('Welcome to Barbarian Developer')
return (<>
<h1>{ text }</h1>
<button onClick={() => setText('Bye bye earthling')}>Say Goodbye</button>
</>);
}
Comments
Post a Comment