how to avoid re-render a child component , I've tested use memo hook it did not work with me can you please help and correct my code .
here is my code
Home Component :
function Home({todos, todoFun }) {
const [ increment ,setIncrement] = useState(1);
const [data , setData] = useState(['test']);
const v = 'some text';
const addValue = () =>{
setData( (data) => [...data, v ]);
}
useMemo(() => data , [data]);
return (
<div>
<h1>{increment}</h1>
<Todos todos ={data} todoFun={addValue}/>
<br />
<button onClick={() => setIncrement(increment => increment + 1)} style={{pading: "20px"}}>
Increment
</button>
</div>
)
}
and from Todos component :
function Index({todos, todoFun }) {
return (
<div>
{console.log('hello from child ')}
{todos.map((todo, index ) =>
{
return <p key={index}>{todo}</p>;
}
)}
<button onClick={todoFun}>Add Text</button>
</div>
)
}
export default memo(Index);
it keep displaying hello from child , when clicking on both buttons
that is how I solved the issue thanks to #Liam's comment , editing add value function :
const addValue = useCallback((e)=>{
setData( (data) => [...data, v ]);
}, [data])
Related
I have array of items and searching items function, that returns another array. When I delete or edit item finded items changes don't render, but when search string has another value React render changes.
I know that useEffect can resolve this problem, but dont what to put in callback.
How can resolve this problem?
export const ToDoList = (props: PropsType) => {
const [searchQuery, setSearchQuery] = useState('')
const searchedItems = useMemo(() => {
return props.ToDoData.filter(item => item.text.includes(searchQuery))
},
[searchQuery])
return (
{props.ToDoData.length ?
<>
<input
...
onChange={e => setSearchQuery(e.target.value)}
/>
<ItemsList
...
items={
searchQuery ?
searchedItems :
props.ToDoData
}
/>
</> :
...
}
)
}
export const ItemsList = (props: PropsType) => {
const [editedText, setEditedText] = useState('')
const onDeleteItem = (id: number) => {
props.dispatch(deleteItem(id))
},
onEditItemMode = (id: number, text: string) => {
props.dispatch(setEditMode(true, id))
setEditedText(text)
},
onEditText = (id: number) => {
props.dispatch(setEditedTextInItem(id, editedText))
props.dispatch(setEditMode(false, id))
setEditedText('')
},
onToggleCompletedStatus = (id: number, status: string) => {
...
}
return (
{props.items.length ?
props.items.map((object) => (
<div
className="Item"
key={object.id}
>
{props.inEditMode.some((id: number) => id === object.id) ?
<>
<input
value={editedText}
onChange={e => { setEditedText(e.currentTarget.value) }}
/>
<button onClick={() => onEditText(object.id)}>
Change text
</button>
</> :
<>
<div className="Item__textBlock">
<input
type='checkbox'
onClick={() => { onToggleCompletedStatus(object.id, object.status)}}
/>
<span className={
object.status === 'completed' ?
'completed' :
'in process'
}>
{object.text}
</span>
</div>
<div className="Item__buttonBlock">
<button
className="Item__button"
disabled={props.inEditMode.length !== 0}
onClick={() => onEditItemMode(object.id, object.text)}
>
<img src={editImg} />
</button>
<button
className="Item__button"
onClick={() => { onDeleteItem(object.id) }}
>
<img src={removeImg} />
</button>
</div>
</>
}
</div>
)) :
...
}
)
}
// This code creates a list that is ONLY updated when searchQuery is updated
const searchedItems = useMemo(() => {
return props.ToDoData.filter(item => item.text.includes(searchQuery))
}, [searchQuery]);
// This code creates the list every time the component renders,
// so it will always be correct
const searchedItems = props.ToDoData.filter(item => item.text.includes(searchQuery))
// If you absolutely need to optimize the render of this component
// This code will update the list whenever the reference for ToDoData is updated as well
const searchedItems = useMemo(() => {
return props.ToDoData.filter(item => item.text.includes(searchQuery))
}, [searchQuery, props.ToDoData]);
I am making a calculator using react.
Every time I press a number button, the whole application re-renders, instead of the <Display />.
To prevent it, I tried 2 different approaches for App, But neither of them worked.
Here is the sandbox link.
Any help would be appreciated.
Put clickHandler inside of useCallback()
const App = () => {
const [screen, setScreen] = useState("0");
console.log("render");
const clickHandler = useCallback(
(val) => {
if (val === "AC") {
setScreen("");
return;
}
screen === "0" ? setScreen(val) : setScreen(screen + val);
},
[screen]
);
return (
<div className="App">
<div className="display">{screen}</div>
<ButtonList clickHandler={clickHandler} />
</div>
);
};
Put Display component inside of React.memo
const App = () => {
const [screen, setScreen] = useState("0");
console.log("render");
const clickHandler = (val) => {
if (val === "AC") {
setScreen("");
return;
}
screen === "0" ? setScreen(val) : setScreen(screen + val);
};
const displayComponent = () => {
return (
<>
<div className="display">{screen}</div>
<ButtonList clickHandler={clickHandler} />
</>
);
};
const MemoizedComponent = React.memo(displayComponent);
return (
<div className="App">
<MemoizedComponent />
</div>
);
};
And here's the ButtonList & Button component.
export const ButtonList = ({ clickHandler }) => {
const arr = [...Array.from(Array(10).keys()).reverse(), "AC"];
return (
<div className="buttons">
<div className="numbersWrapper">
{arr.map((item) => (
<Button
key={item}
clickHandler={clickHandler}
value={item.toString()}
/>
))}
</div>
</div>
);
};
export const Button = ({ value, clickHandler }) => {
return (
<button
name={value}
onClick={() => {
clickHandler(value); //where the clickEvent happens
}}
>
{value}
</button>
);
};
If you don't want a component re-render,You would have to define the click handler in another component that you would like to re-render.
So do it like this:
const App = () => {
console.log("render");
return (
<div className="App">
<childComponent />
</div>
);
};
export const childComponent = () => {
const [screen, setScreen] = useState("0");
const clickHandler = (val) => {
if (val === "AC") {
setScreen("");
return;
}
screen === "0" ? setScreen(val) : setScreen(screen + val);
};
return (
<>
<div className="display">{screen}</div>
<ButtonList clickHandler={clickHandler} />
</>
);
}
This way you prevent a particular component from re-rendering. But note that if you update a state or do anything from which causes re-renders from the parent component, It would equally re-render the child component.
const CompleteDriverInfo = () => {
const [DriverInfo, setDriverInfo] = useState([]);
useEffect(async () => {
await setDriverInfo(await GetFetch('driver'));
}, []);
return (
<div>
<Link to='/adddriver'>
<button className='btn btn-primary'>Add Driver</button>
</Link>
{DriverInfo.map((EachDriver) => (
<EachDriverInfo EachDriver={EachDriver} />
))}
</div>
);
};
const EachDriverInfo = ({ EachDriver }) => {
const DeleteDriver = (e) => {
POST(
'deletedriver',
{
CustomerName: EachDriver.CustomerName,
},
e
);
};
return (
<>
<h1>Name: {EachDriver.CustomerName}</h1>
<h1>Phone Number: {EachDriver.PhoneNumber}</h1>
<h1>Email: {EachDriver.Email}</h1>
<h1>Address: {EachDriver.Address}</h1>
<h1>Country: {EachDriver.Country}</h1>
<button onClick={(e) => DeleteDriver(e)} className='btn btn-primary'>
Delete Driver
</button>
</>
);
};
When I click Delete Driver in my child component, it deletes a driver from the database, but the page doesn't re-render until refresh because of useEffect's empty dependencies.
I was thinking of setting a parent state from the child component and putting that in the dependency array but it feels like an anti-pattern
It is perfectly fine to update parent state from the child component. Just pass a function to the child component, and when child component changes the state, call this function inside the child component so that the parent component can update the app state and the rerender.
Here is a sample codesandbox:
import React, { useState, useEffect } from "react";
import axios from "axios";
const Posts = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
const getPosts = async () => {
const response = await axios.get(
`https://jsonplaceholder.typicode.com/posts`
);
setPosts(response.data);
};
getPosts();
}, []);
const handleDeletePost = (id) => {
const updatedPosts = posts.filter((p) => p.id !== id);
setPosts(updatedPosts);
};
return (
<div>
{posts.map((post) => (
<PostInfo key={post.id} post={post} deletePost={handleDeletePost} />
))}
</div>
);
};
const PostInfo = ({ post, deletePost }) => {
const DeletePost = async (id) => {
await axios.delete(`https://jsonplaceholder.typicode.com/posts/{id}`);
deletePost(id);
};
return (
<>
<h1>Id: {post.id}</h1>
<h1>Title: {post.title}</h1>
<button onClick={() => DeletePost(post.id)} className="btn btn-primary">
Delete Post
</button>
</>
);
};
export default Posts;
I'm trying to figure out how to edit a todo item in my react app using hooks, but I can't seem to figure out how to write the code.
Most of the solutions I've seen online are using class components and it's not written with the same logic as my app.
Here is my current code
function TodoList() {
const [todos, setTodos] = useState([]);
const addTodo = todo => {
if (!todo.text || /^\s*$/.test(todo.text)) {
return;
}
const newTodos = [todo, ...todos];
setTodos(newTodos);
console.log(newTodos);
};
const removeTodo = id => {
const removedArr = [...todos].filter(todoId => todoId.id !== id);
setTodos(removedArr);
};
const completeTodo = id => {
let updatedTodos = todos.map(todo => {
if (todo.id === id) {
todo.isComplete = !todo.isComplete;
}
return todo;
});
setTodos(updatedTodos);
};
const editTodo = e => {
setTodos(e.target.value);
};
return (
<>
<TodoForm onSubmit={addTodo} />
{todos.map(todo => (
<div>
<div
key={todo.id}
className={todo.isComplete ? 'complete' : ''}
key={todo.id}
onClick={() => completeTodo(todo.id)}
>
{todo.text}
</div>
<FaWindowClose onClick={() => removeTodo(todo.id)} />
</div>
))}
</>
);
}
Here is the code from the other component
function TodoForm(props) {
const [input, setInput] = useState('');
const handleChange = e => {
setInput(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
props.onSubmit({
id: Math.floor(Math.random() * 10000),
text: input,
complete: false
});
setInput('');
};
return (
<form onSubmit={handleSubmit}>
<input
placeholder='todo...'
value={input}
onChange={handleChange}
name='text'
/>
<button onClick={handleSubmit}>add todo</button>
</form>
);
}
So right now everything works where I can add todos and delete todos + cross out todos. Only thing missing is being able to edit them.
I saw some suggestions about updating the text value with an input form, but I'm not too sure how I'd implement that in my editTodo function.
Similar to your removeTodo handler, you want to pass the todo.id to completeTodo.
<div className={todo.isComplete ? "complete" : ""} key={todo.id} onClick={() => completeTodo(todo.id)}>
Then you would update a bool value in the todo object.
const completeTodo = (id) => {
let updatedTodos = todos.map(todo => {
if(todo.id === id){
todo.isComplete = true
}
return todo
})
setTodos(updatedTodos)
};
Edit: add styling strikethrough
You'll then conditionally add a css style based on isComplete boolean
CSS
.complete {
text-decoration: line-through;
}
To be able to click on the Remove button, place it outside the todo div in your map function.
{todos.map((todo, isComplete) => (
<>
<div
key={todo.id}
onClick={completeTodo}
className={isComplete ? 'complete' : ''}
>
{todo.text}
</div>
<FaWindowClose onClick={() => removeTodo(todo.id)} />
</>
))}
As discussion with you in another question here it is:
TodoList.js
import React, { useState } from "react";
import TodoForm from "./TodoForm";
import Todo from "./Todo";
function TodoList({ onClick }) {
const [todos, setTodos] = useState([]);
//Track is edit clicked or not
const [editId, setEdit] = useState(false);
//Save input value in input box
const [inputValue, setInputValue] = useState("");
const handleEditChange = (id, text) => {
setEdit(id);
setInputValue(text);
};
const addTodo = (todo) => {
if (!todo.text || /^\s*$/.test(todo.text)) {
return;
}
const newTodos = [todo, ...todos];
setTodos(newTodos);
console.log(newTodos);
};
const removeTodo = (id) => {
const removedArr = [...todos].filter((todoId) => todoId.id !== id);
setTodos(removedArr);
};
const completeTodo = (id) => {
let updatedTodos = todos.map((todo) => {
if (todo.id === id) {
todo.isComplete = !todo.isComplete;
}
return todo;
});
setTodos(updatedTodos);
};
const editTodo = (id, text) => {
let editTodos = todos.map((todo) => {
if (todo.id === id) {
todo.text = text;
}
return todo;
});
setTodos(editTodos);
setEdit(false);
};
return (
<>
<TodoForm onSubmit={addTodo} />
{/* I want to move this code below into a new component called Todo.js */}
<Todo
todos={todos}
completeTodo={completeTodo}
removeTodo={removeTodo}
editTodo={editTodo}
handleEditChange={handleEditChange}
editId={editId}
inputValue={inputValue}
setInputValue={setInputValue}
/>
</>
);
}
export default TodoList;
Todo.js
// I want to move this code into this component
import React, { useState } from "react";
import { FaWindowClose, FaRegEdit } from "react-icons/fa";
const Todo = ({
todos,
completeTodo,
removeTodo,
editTodo,
editId,
handleEditChange,
inputValue,
setInputValue
}) => {
return todos.map((todo) => (
<div className="todo-row">
{editId === todo.id ? (
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
) : (
<div
key={todo.id}
className={todo.isComplete ? "complete" : ""}
onClick={() => completeTodo(todo.id)}
>
{todo.text}
</div>
)}
{editId === todo.id ? (
<button onClick={() => editTodo(todo.id, inputValue)}>Edit todo</button>
) : (
<>
<FaWindowClose onClick={() => removeTodo(todo.id)} />
<FaRegEdit onClick={() => handleEditChange(todo.id, todo.text)} />
</>
)}
</div>
));
};
export default Todo;
Make sure you read and understand code first. Logic is pretty simple what you do in completeTodo. You just need to update text part. Tricky part is to open in input. So logic is like track if user click on id set that id. And check if id is there open input with that id value other wise normal one.
Here is demo of this POC: https://codesandbox.io/s/nostalgic-silence-idm21?file=/src/Todo.js:0-1059
App won't re render different data on state change.
State does change in the dev tools but doesn't show on page.
Using button to filter.
export const StoriesPage = () => {
const [storyIds, setStoryIds] = useState([]);
const [storyUrl, setStoryUrl] = useState('top');
useEffect(() => {
let url = baseUrl;
storyUrl === 'top'
? (url += 'topstories.json')
: (url += 'newstories.json');
getStoryIds(url).then(data => setStoryIds(data));
}, [storyUrl]);
return (
<div>
<div>
<button onClick={() => setStoryUrl('new')}>New</button>
<button onClick={() => setStoryUrl('top')}>Top</button>
</div>
{storyIds.map((storyId, index) => (
<Story key={index} storyId={storyId} />
))}
</div>
);
};
Added a function that clears storyIds before setStoryUrl
const handleFilter = tag => {
setStoryIds([]);
setStoryUrl(tag);
};