React Hooks, useRef, useState and Props with Practical Examples for Beginners
The provided React code demonstrates the use of the useRef
hook to access and manipulate a text input field directly. In the App
component, a reference (inputRef
) is created using useRef
, which is assigned to an input element. This allows the component to access the current value of the input without needing to store it in state. When the “Submit” button is clicked, the current value of the input field is logged to the console using inputRef.current.value
. This approach highlights how useRef
can simplify interactions with the DOM and manage input values in a React application, making it useful for scenarios where direct access to a DOM element is needed without triggering re-renders.
const App = () => {
const a = “Hello React”;
const abc = [“Salesman 1”, “Salesman 2”, “Salesman 3”];
return (
<>
{a}
{abc.map((hello)=>{return <h2>{hello}</h2>})}
</>
)
}
export default App
1. Mapping Through an Array to Display Elements
Explanation: This component maps over an array (abc
) and renders each item as an <h2>
element. It also displays the string a
at the top.
Key Concept: Array mapping is commonly used in React to dynamically render lists of elements.
2. Conditional Rendering with a String
const App = () => {
const boy = “hello”
return (
<>
{boy===”hello”?<h1>How are you</h1> : <h1>I am doing well</h1>}
</>
)
}
export default App
Explanation: This component displays a message based on the value of the boy
variable. If boy
equals "hello"
, it shows “How are you”; otherwise, it shows “I am doing well”.
Key Concept: Conditional rendering allows different content to be displayed based on specific conditions.
3. Increment Variable on Button Click
const App = () => {
var a = 1;
const hereClick = () => {
console.log(“Clicked Number one”);
a++;
console.log(a);
}
return (
<>
{a}
<button onClick={()=>{hereClick()}}>CLICK ON BOMB</button>
<FirstComponent data={a} />
</>
)
}
export default App
Explanation: This component increments the variable a
each time the button is clicked. However, a
is not stored in the component’s state, so it doesn’t trigger a re-render when updated, meaning the UI won’t update.
Key Concept: React doesn’t track variable changes unless they are part of the component’s state (useState
should be used).
4. This program introduces state management with useState
import { useState } from “react”;
const App = () => {
const [a, setA] = useState(0);
const hereClick = () => {
console.log(“Clicked Number of Times”);
setA(a+1);
console.log(a);
}
return (
<>
{a}
<button onClick={()=>{hereClick()}}>Click on Button</button>
<FirstComponent data={a} />
</>
)
}
export default App
const FirstComponent = ({data}) => {
return (
<div>FirstComponent {data}</div>
)
}
export default FirstComponent
- Initializes
a
with a default value of0
. ThesetA
function is used to updatea
and trigger a re-render of the component whena
changes.
- Declares the
hereClick
function, which will handle the button click event. Inside this function, we log a message and increment the value ofa
.
- Updates the value of
a
by incrementing it by 1. Sincea
is part of the state, this change will trigger a re-render of the component.
- Logs the current value of
a
to the console. Note: this may log the previous value becausesetA
doesn’t updatea
immediately; React batches state updates.
- Displays the current value of (a) in the UI.
- A button that, when clicked, triggers the
hereClick
function to update the value ofa
and log messages to the console.
- Passes the current value of
a
as a prop (data
) to theFirstComponent
. This demonstrates how to pass state or data from one component (parent) to another (child).
Incrementing State and Passing Props in React
import { useState } from “react”;
import FirstComponent from “./conponents/FirstComponent”;
const App = () => {
const [a, setA] = useState(0);
const hereClick = () => {
console.log(“Clicked Number one”);
setA(a+1);
console.log(a);
}
return (
<>
<button onClick={()=>{hereClick()}}>CLICK ON BOMB</button>
<FirstComponent data={a} fn={setA}/>
</>
)
}
export default App
const FirstComponent = ({data, fn}) => {
return (
<div>
<button onClick={()=>{fn(10)}}>Set 10</button>
FirstComponent {data}
</div>
)
}
export default FirstComponent
- This line initializes a piece of state a with an initial value of 0. The setA function is used to update the value of a and cause the component to re-render.
- A function called hereClick is defined to handle the button click event. It will log a message and increment the value of a.
- Increases the value of a by 1. This triggers a re-render of the component, and the new value of a will be passed down to FirstComponent as a prop.
- Logs the current value of a to the console. Note that the log will display the previous value of a because React’s state updates are asynchronous.
- { hereClick() }}>CLICK ON BOMB
FirstComponent
and how it integrates with the App
component:
FirstComponent
receives two props from the parent (App
) component:data
: This contains the current state value (a
) from theApp
component.fn
: This is thesetA
function (passed from the parent) used to update the value ofa
inApp
.- This button, when clicked, invokes the
fn
function passed from the parent, which is essentiallysetA(10)
. This updates the statea
in the parent (App
) to10
, triggering a re-render ofApp
and passing the updated value toFirstComponent
as a prop. - Displays the value of
data
(which is equivalent toa
fromApp
) in the component. The displayed value updates whenevera
changes.
Explanation of the FirstComponent
and how it integrates with the App
component:
- Receiving Props (
data
andfn
):jsxCopy codeconst FirstComponent = ({ data, fn }) => {
FirstComponent
receives two props from the parent (App
) component:data
: This contains the current state value (a
) from theApp
component.fn
: This is thesetA
function (passed from the parent) used to update the value ofa
inApp
.
- Button in
FirstComponent
:jsxCopy code<button onClick={() => { fn(10) }}>Set 10</button>
- This button, when clicked, invokes the
fn
function passed from the parent, which is essentiallysetA(10)
. This updates the statea
in the parent (App
) to10
, triggering a re-render ofApp
and passing the updated value toFirstComponent
as a prop.
- This button, when clicked, invokes the
- Displaying the
data
:jsxCopy codeFirstComponent {data}
- Displays the value of
data
(which is equivalent toa
fromApp
) in the component. The displayed value updates whenevera
changes.
- Displays the value of
Integration with the App
Component:
- In the
App
component, we are passing two props toFirstComponent
:data={a}
: The current state valuea
(initially0
).fn={setA}
: ThesetA
function, which allowsFirstComponent
to modify the value ofa
.
- When the user clicks the “Set 10” button in
FirstComponent
, thefn(10)
call updatesa
to10
in theApp
component. This triggers a re-render inApp
, andFirstComponent
will then display the updated value (10
).
How It Works Together:
- The
App
component controls the state (a
) and renders theFirstComponent
. FirstComponent
receives the current value ofa
and the function (setA
) to modify it.- The two components communicate through props:
App
passes down data (a
) and a function (setA
) to allowFirstComponent
to update the parent’s state.
This component demonstrates how to use useRef
to manage input field values without state, providing a direct way to interact with DOM elements in React.
import { useRef } from “react”
const App = () => {
const inputRef = useRef(null);
return (
<>
<input type=”text” ref={inputRef} />
<button onClick={()=>{console.log(inputRef.current.value);
}}>Submit</button>
</>
)
}
export default App
- Imports the
useRef
hook from React, which is used to create a mutable reference that persists for the lifetime of the component. - Initializes a reference (inputRef) that will be attached to an input element. The initial value is set to null.
- Renders an input field of type text and assigns the inputRef to its ref attribute. This allows direct access to the DOM element.
- Renders a button. When clicked, it logs the current value of the input field to the console by accessing inputRef.current.value.
- inputRef.current provides direct access to the underlying DOM element, allowing you to read its value without needing to store it in the component’s state.
Leave a Reply
You must be logged in to post a comment.
Leave a Comment