Understanding state in reactjs? - javascript

I am learning Reactjs. And I am building Counter App. I think the code below and state in react
are the same. console.log print correctly but in the html it doesn't change the value. Can you explain to me why the code didn't work?
import React, {useState} from "react";
let count = 0;
const Counter = (props) => {
const setCount = ()=> {
count = count + 1;
};
return (
<div>
<button onClick={()=> {
setCount();
console.log('counter: ', count);
}}>button</button>
<div>Hello {props.name} and your current number is: {count} </div>
</div>
)
};
export default Counter;

Changing a variable does not rerender the component.
To see updates in the dom you must rerender a component. There are a few ways to do this.
changing the state
changing the props
changing the context
if you put the count variable in a state and trigger it from there you will see it update in the component
Example form the docs
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

html should be rendered with the new value once button is clicked, this is where the state and setstate methods comes to play. setcount means setcount will change the value and refreshes or say rerender the html with the value.

Well.. that's why state is there for.. It essentially tells your component to REACT, to its change.
If you want your DOM to respond to the change of a variable, You need to bind it to a state variable.
Your code below, will only change the variable, but won't trigger any re-rendering. That's why you could see the change in console, but not in DOM.
const setCount = ()=> {
count = count + 1;
};

First of all, according to React docs, a component re-renders only when a state or a props(used in the component) updates. So change in a variable doesn't affect the rendering of the component. If variable change affects the component, then there would be no need of using this library. Learn about setState. Hope it helps!.. Happy coding! ..

Related

Re-rendering behavior with class and functional component - ReactJS

I did a lot of research about Impure component vs Pure component, I am so confused about it and their behavior with Class & Functional components. So, please read carefully.
Question #1:
Is the definition of pure component is that "Pure component doesn't re-render when the value of changed state is the same value as the previous one", right?
Question #2 I can see that Functional Component behaves as pure component by default, because it doesn't re-renders the component if incoming state value is same as current one, am i right?.
const Home = () => {
const [count, setCount] = useState(1)
const handleCount = () => {
setCount(1)
}
console.log(`HOME ${count} - Functional Component`);
return (
<div>
<button onClick={handleCount}>Click Me</button>
<div>{count + 1}</div>
</div>
)
}
export default Home
See, It doesn't re-render when I click on button. Then it means functional components are pure components by default, right?
Question #3: Using functional component, when I set the default state to 0 and then call the setState like: setCount(1) then it should re-render only on first click because state has changed. But, when I click on 2nd time on button, it again re-renders, even current state value (1) is equal to incoming state (1), then why it re-renders on same value in functional component?
const [count, setCount] = useState(0)
const handleCount = () => {
setCount(1)
}
I am so much confused with different definitions and different behaviors again and again.
Can someone help me with this?
Question #4: When component re-renders? On setState function call or when state value updates?
Question #5: If my default state value is true, and i call the update function like: setState(true). Will it still update the state value or it will not update the state value because it's same?

React: Re-render component when prop change

Why child component displays updated prop value only when I'm using useState?
For example:
It works when I'm calling setReRender() with any random values.
Parent Component (demo code):
import Child from './Child';
const Parent = () => {
const [arr, setArr] = useState([]);
const [reRender, setReRender] = useState(" ");
return (
<>
{arr.map(client => {
return(
<Child
setReRender={setReRender}
arr={arr}
firstName={client.firstName}
lastName={client.lastName}
/>
);
})}
</>
)
}
The update will be displayed on the screen only after I'm calling setReRender().
For example- it works with setReRender(Math.random() * 2).
useEffect supposed to listen for update or change etc. but I didn't know that it will work with useState.
Is this the right way to make the parent component re-render itself?
Edit:
Apologies if my question isn't clear enough, it's my first time here.
The component re-renders automatically if there is a change in state, so when you are calling it with random values you are changing the state of the component and it is being re-rendered
Can you describe what your program is trying to do?

How does useState hook know the calling context in react

I am switching from using class components into using functional components in React. I read through their documentation and I like to know how the useState hook work.
In their FAQ they the same question that I'm asking, by saying that each component have a internal list: for storing the state variables, and that the useState know the calling component for storing the state variable.
I want to know how does useState know the calling component since we don't pass it anything other than the initial state value.
Can someone explain me this with a example? I really want to know how this work.
In short, at the begining of render a component, React generate a value like currentComponentContext. When you call useState, React will bind this state with currentComponentContext.
see function mountState and dispatchAction in ReactFiberHooks.new.js, react bind the state with currentlyRenderingFiber.
useState is the state hook provided by react. It returns a “pair” the current state value and a function to update it and also takes a single argument which is the initial value that you want to assign for the state variable.
In the above example count is the state variable and setCount is the function for changing the value and 0 is the default value we are assigning to count. In this example we used a counter as integer value just for demonstration, but we can use any other type like string, object, array etc also we can use multiple state variables defined in a single component.
import React, { useState } from 'react;
const MyComponent = (props) => {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment Count
</button>
<button onClick={() => setCount(count - 1)}>
Decrement Count
</button>
</div>
)
}
export const MyComponent;
Assuming that seterInClass is an arrow function define to set the value of the variable username.
setterInClass = (val) =>{
this.setState({username:val});
}
in a class the initialization is through this.state
in a functional it is through the userState which acts as a glue.
this.state = {username:''} + setterInClass is equivalent to const [username, setUsername] = useState('').
Meaning useState is establishing a relation of setter to the variable username, after initializing it; And avoid us to write this.state to get the value of any variable or having top write const {username} = this.state;
So it is cleaner, less code for us and make functionals component looks cute
"useState" returns an array with two items. In the first index you have the state itself and in the second index you will get a function to handle that state.
Do this and you will understand :
const useStateArray = useState();
console.log(useStateArray[0]);
console.log(useStateArray[1]);

How are hooks internally implemented?

Lately i have been reading about hooks and was curious to know how they are internally implemented.
import React, { useState } from 'react';
function CounterUsingHooks() {
const [count, setCounter] = useState(5);
return (
<div>
<button onClick={() => setCounter(count + 1)}>
{count}
</button>
</div>
);
}
I understand that UseState accepts initial value and returns a pair which upon array destruction gets set as count and setCounter, where count is set to the first value returned by useState, and setCounter is the second.
I'm just interested in binding the function to the variable part.
why is it required to assign to UseState ? taking above example i can just write as below :
var count;
var setCounter=function(count){
count= count+1;
}
Could someone please explain me how exactly is UseState implemented ?
First, you need to understand the Fundamentals of State in React.
State is a JavaScript object that stores a component’s dynamic data and determines the component’s behaviour. Because state is dynamic, it enables a component to keep track of changing information in between renders and for it to be dynamic and interactive.

Updating Global Variable / State in React

Still quite new to React and have been working on a project. I've been needing to keep track of this counter as a global variable and update its value inside a component. I've declared this counter using the setState hook const [currentMaxRow, setRow] = useState(3) and I want to update this value inside the component it's being passed into. Not really sure how to go about this, thanks!
Sample application using hooks
-passing value and function to child component.
function App() {
const [currentMaxRow, setRow] = React.useState(3)
const incrementVal = () => {
setRow(currentMaxRow + 1);
};
return (
<div>
<p>You clicked {currentMaxRow} times</p>
<Child count={currentMaxRow} incrementVal={incrementVal} />
</div>
);
}
const Child = props => (
<>
<button onClick={props.incrementVal}>Click me</button>
<h3>{props.count}</h3>
</>
);
This is actually quite straightforward. The only thing you need to do is to also pass the "setRow" function to your child component. Now anytime you want to update the state in the parent, you basically call the function prop inside your child component.
However, I think it's worth mentioning that a component's state and a global variable are not the same thing. I highly recommend you read the React documentation regarding components, state and props. It'll clear things up a whole lot more!

Categories

Resources