title | description | canonical |
---|---|---|
useState Hook | Details about the useState React hook in ReScript | /docs/react/latest/hooks-state |
React.useState
returns a stateful value, and a function to update it.
<CodeTab labels={["ReScript", "JS Output"]}>
let (state, setState) =React.useState(_=>initialState)
varmatch=React.useState(function(){returninitialState;});varstate=match[0];varsetState=match[1];
During the initial render, the returned state state
is the same as the value passed as the first argument (initialState).
The setState
function can be passed down to other components as well, which is useful for e.g. setting the state of a parent component by its children.
@react.componentletmake= () => { let (text, setText) =React.useState(_=>""); letonChange=evt=> { ReactEvent.Form.preventDefault(evt) letvalue=ReactEvent.Form.target(evt)["value"] setText(_prev=>value); } <div> <inputonChangevalue=text /> </div> };
In this example, we are creating a ThemeContainer
component that manages a darkmode
boolean state and passes the setDarkmode
function to a ControlPanel
component to trigger the state changes.
<CodeTab labels={["ReScript", "JS Output"]}>
// ThemeContainer.resmoduleControlPanel= { @react.componentletmake= (~setDarkmode, ~darkmode) => { letonClick=evt=> { ReactEvent.Mouse.preventDefault(evt) setDarkmode(prev=>!prev) } lettoggleText="Switch to "++ ((darkmode ? "light" : "dark") ++" theme") <div> <buttononClick> {React.string(toggleText)} </button> </div> } } @react.componentletmake= (~content) => { let (darkmode, setDarkmode) =React.useState(_=>false) letclassName=darkmode ? "theme-dark" : "theme-light" <divclassName> <section> <h1> {React.string("More Infos about ReScript")} </h1> content </section> <ControlPaneldarkmodesetDarkmode /> </div> }
functionControlPanel(Props){varsetDarkmode=Props.setDarkmode;vardarkmode=Props.darkmode;varonClick=function(evt){evt.preventDefault();returnCurry._1(setDarkmode,(function(prev){return!prev;}));};vartoggleText="Switch to "+((darkmode ? "light" : "dark")+" theme");returnReact.createElement("div",undefined,React.createElement("button",{onClick: onClick},toggleText));}functionThemeContainer(Props){varcontent=Props.content;varmatch=React.useState(function(){returnfalse;});vardarkmode=match[0];varclassName=darkmode ? "theme-dark" : "theme-light";returnReact.createElement("div",{className: className},React.createElement("section",undefined,React.createElement("h1",undefined,"More Infos about ReScript"),content),React.createElement(Playground$ControlPanel,{setDarkmode: match[1],darkmode: darkmode}));}
Note that whenever setDarkmode
is returning a new value (e.g. switching from true
-> false
), it will cause a re-render for ThemeContainer
's className
and the toggle text of its nested ControlPanel
.