Basic React Hooks explained - useState

React Hooks

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?


When you use the "setValue" function to set the value of the state variables, the component gets re-rendered. 

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

Popular posts from this blog

What is Base, Local & Remote in Git merge

Asynchronous Nunjucks with Filters and Extensions

Debug Azure Function locally with https on a custom domain