Local state
When we alter something in a React component, React effectively only re-renders that which was changed in the DOM. Now, even though you might adjust something in a React component, this doesn't mean this component will automatically be re-rendered.
This is something you can do by making use of State.
State and React hooks
State helps you re-render your React component after something needs to be changed. A user opens a menu overlay? State. Displaying a custom error message for a form? State.
Working with state can be done through a React concept called hooks. Hooks are a feature that let you “hook into” React functions which help you manage your application. Creating a state can be achieved with a react Hook called useState
, which both keeps track of the state and allows you to change it. Before we dive in, mounting a large component can take a second. Therefore, it's always worth considering using CSS to hide it rather than unmounting it.
As mentioned before, when you want to add interactivity to your components, you need to make sure you're using client components instead of server components. Using React hooks in a server component will not work. Turn a server component into a client component by using the "use client"
directive at the top of the file.
"use client" // It doesn't work in this live example, but don't forget to import useState :) // import { useState } from 'react' export const Toggle = (props) => { const [isActive, setIsActive] = useState(false); const handleClick = () => setIsActive(!isActive); return ( <> <button onClick={handleClick}>toggle</button> {isActive && ( <nav> <hr/> <ol> <li><a href="#">Home</a></li> <li><a href="#">Bikes</a></li> <li><a href="#">Mountains</a></li> </ol> </nav> )} </> ) }
- We initiate the
useState
hook which can be read (isActive
) and altered (setIsActive
). As a convention we use the prefixset
to indicate that this variable alters the state. The value starts out beingfalse
; - We create a function that updates the state by inversing the boolean value;
- We render the component and update the state with the
onClick
event.
When a React component is re-rendered it preserves the useState
value, but reloads regular variables.